golang中runtime.Gosched()的理解
来源:互联网 发布:大数据案例 编辑:程序博客网 时间:2024/06/09 20:56
runtime.Gosched()用于让出CPU时间片。这就像跑接力赛,A跑了一会碰到代码runtime.Gosched()就把接力棒交给B了,A歇着了,B继续跑。
看代码:
package main import ("fmt""runtime") func say(s string) {for i := 0; i < 2; i++ {runtime.Gosched()fmt.Println(s)}} func main() {go say("world")say("hello")}
输出结果:
hello
world
hello
注意结果:
1、先输出了hello,后输出了world.
2、hello输出了2个,world输出了1个(因为第2个hello输出完,主线程就退出了,第2个world没机会了)
把代码中的runtime.Gosched()注释掉,执行结果是:
hello
hello
因为say("hello")这句占用了时间,等它执行完,线程也结束了,say("world")就没有机会了。
这里同时可以看出,go中的goroutins并不是同时在运行。事实上,如果没有在代码中通过
runtime.GOMAXPROCS(n) 其中n是整数,
指定使用多核的话,goroutins都是在一个线程里的,它们之间通过不停的让出时间片轮流运行,达到类似同时运行的效果。
还需要学习一句话:
当一个goroutine发生阻塞,Go会自动地把与该goroutine处于同一系统线程的其他goroutines转移到另一个系统线程上去,以使这些goroutines不阻塞
0 0
- golang中runtime.Gosched()的理解
- Golang中位运算的详细理解
- OC 中runtime的理解 以及 使用
- runtime 中OC理解
- golang runtime-gdb.py的问题
- golang打印所有的runtime调用栈
- runtime的个人理解
- 关于runtime的理解
- 对runtime的理解
- Runtime的理解
- iOS runtime的理解
- runtime的简单理解
- runtime的理解
- 理解OC的Runtime
- runtime的理解
- iOS runtime的理解
- Ios runtime的理解
- 对Runtime的理解
- poj 1724 ROADS
- centos 将 eth1 修改为 eth0 并修改 hostname
- 自定义返回按钮,会出现没有侧滑按钮,会出现屏幕卡屏导致推不过去。
- JSP 千位分隔符
- LeetCode Verify Preorder Serialization of a Binary Tree
- golang中runtime.Gosched()的理解
- ScrollBottom计算方法
- 2016年最值得关注的5大营销思维变革
- return View
- hadoop3---DistCp 并行文件复制
- 改变app的语言
- 无聊时总结总结算法之02排序(直接插入+希尔)
- Java cookie和session介绍与区别
- Install OpenCV 3.0 and Python 2.7+ on OSX