简体   繁体   English

goroutine如何共享CPU资源?

[英]how do go goroutines share CPU resources?

Say I launch more goroutines than I have cores in my CPU. 假设我启动的goroutine超过了我的CPU中的内核。 How do they share the CPU resource? 他们如何共享CPU资源? Do they run for a certain amount of time, then sleep for a bit? 他们会跑步一定时间,然后睡一会吗? Do they run for as long as they are CPU bound then exit, allowing CPU-starved goroutines to run? 它们是否在受CPU约束然后退出的时间内运行,从而允许CPU匮乏的goroutine运行?

The Go scheduler handles the sharing of the the CPU resources among goroutines. Go调度程序处理goroutine之间CPU资源的共享。

I believe it's currently a cooperative scheduler, which means your code needs to give the scheduler opportunities to context-switch to other goroutines, by either making system calls / function calls, or using the synchronization primitives like atomic, mutex, or channel operations. 我认为它目前是一个协作式调度程序,这意味着您的代码需要通过进行系统调用/函数调用或使用原子,互斥或通道操作等同步原语,使调度程序有机会上下文切换到其他goroutine。

If you just run tight loops in your goroutines without any of the above, it will starve other goroutines and the Go scheduler and garbage collector as well, so beware. 如果您只是在goroutine中运行紧密循环而没有上述任何操作,它将使其他goroutine和Go调度程序以及垃圾收集器都饿死,因此请当心。

It looks like some preemptive scheduling techniques might be planned for Go1.12, see here: 看起来可能会为Go1.12计划一些抢占式调度技术,请参见此处:

https://github.com/golang/go/issues/24543 https://github.com/golang/go/issues/24543

Further reading on the Go scheduler: 有关Go调度程序的进一步阅读:

https://www.ardanlabs.com/blog/2018/08/scheduling-in-go-part2.html https://www.ardanlabs.com/blog/2018/08/scheduling-in-go-part2.html

Goroutines are cooperatively scheduled. Goroutine是协作调度的。 Does that mean that goroutines that don't yield execution will cause goroutines to run one by one? 这是否意味着不产生执行结果的goroutine将导致goroutine逐一运行?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM