How the Go Scheduler Works

G, M, P Model

The Go scheduler uses the GMP model to map Goroutines to OS threads via logical processors for efficient, balanced concurrency.

The Go scheduler uses a GMP model where Goroutines (G) are scheduled onto OS threads (M) via logical processors (P) to manage concurrency efficiently. A P holds a local queue of runnable Gs and executes them on its bound M, stealing work from other Ps if its queue empties to ensure balanced load across all CPU cores.

// Conceptual GMP relationship in runtime
// G: Goroutine (user task)
// M: OS Thread (execution context)
// P: Logical Processor (holds G queue, binds to M)

// 1. G is created and added to a P's local run queue.
// 2. M picks up a P and executes Gs from that P's queue.
// 3. If P's queue is empty, M steals Gs from another P's global queue.
// 4. If M blocks (e.g., syscall), it releases P so another M can use it.