Say I launch more goroutines than I have cores in my CPU. How do they share the CPU resource? 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?
1 Answers
The Go scheduler handles the sharing of the the CPU resources among goroutines.
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.
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.
It looks like some preemptive scheduling techniques might be planned for Go1.12, see here:
https://github.com/golang/go/issues/24543
Further reading on the Go scheduler:
https://www.ardanlabs.com/blog/2018/08/scheduling-in-go-part2.html

- 7,275
- 1
- 26
- 29
-
Another resource with references at the bottom. Article is 2 years old, however... https://rakyll.org/scheduler/ .. and of course, the source code itself: https://github.com/golang/go/blob/master/src/runtime/proc.go – RayfenWindspear Jan 06 '19 at 15:02