Golang & Concurrency (50 Qs)•Part 2: Concurrency, Channels & The GMP Scheduler (16 - 32)
How does the Go GMP Scheduler work (Goroutines, Machines, and Processors)?
senior LevelCode ExampleGolang
In Simple Words: Go multiplexes $N$ user-space Goroutines onto $M$ OS kernel threads using $P$ logical execution processors:
- G (Goroutine): Represents the goroutine (stack, instruction pointer, state).
- M (Machine / OS Thread): Created by the OS kernel to execute code.
- P (Processor): Logical context required to execute Go code (capped at
GOMAXPROCS, defaulting to the number of CPU cores).
Work-Stealing Algorithm:
Each P maintains a local run queue of 256 goroutines. If a P exhausts its local queue, it steals half the goroutines from another P's run queue, balancing workload across all CPU cores with zero lock contention.
css
[ P0 Local RunQueue ] [ P1 Local RunQueue ]
│ │
[M0] [M1] <-- OS Kernel Threads
│ │
[CPU Core 0] [CPU Core 1]