Junior — Middle
How is the distribution of four goroutines across four processor cores handled when they are launched?
sobes.tech AI
Answer from AI
In Go, the goroutine scheduler (Goroutine scheduler) distributes goroutines across system threads (M), which are in turn bound to CPU cores.
If you have 4 goroutines and 4 CPU cores, the scheduler can assign each goroutine to a separate core, enabling parallel execution. This is possible if the environment variable GOMAXPROCS is set to 4 (by default, in modern Go versions, it is set to the number of available cores).
Example:
runtime.GOMAXPROCS(4) // set the number of available threads to 4
for i := 0; i < 4; i++ {
go func(id int) {
fmt.Printf("Goroutine %d started\n", id)
// work
}(i)
}
The Go scheduler will distribute goroutines across threads that can run on different cores, allowing efficient use of multi-processor systems. However, the exact distribution depends on system load and the internal scheduler.