Middle+
How are parallel computations organized in Go? Tell me about the goroutine scheduler.
sobes.tech AI
Answer from AI
In Go, parallel computations are implemented through goroutines — lightweight threads managed by the Go runtime. The goroutine scheduler is responsible for distributing many goroutines across a limited number of system threads (OS threads).
The scheduler is based on an M:N model, where M is the number of system threads, and N is the number of goroutines. Main components:
- G (goroutine) — a structure describing a goroutine.
- M (machine) — a system thread that executes goroutines.
- P (processor) — a logical processor that connects M and G, managing the queue of ready goroutines.
Scheduler operation:
- There is a pool P, usually equal to the number of available CPUs (GOMAXPROCS).
- Each P has a queue of ready goroutines.
- M is bound to a P and executes a goroutine from its queue.
- If a goroutine blocks (e.g., on I/O), M can switch to another goroutine.
The scheduler allows efficient use of multi-core systems, quick switching between goroutines, and minimizes overhead compared to system threads.
Example of starting a goroutine:
func worker(id int) {
fmt.Printf("Worker %d started\n", id)
// work
}
func main() {
for i := 0; i < 5; i++ {
go worker(i) // start goroutine
}
time.Sleep(time.Second) // wait for completion
}