GMP — Goroutine (G), Machine (M), Processor (P). Go uses this three-level scheduler to efficiently multiplex goroutines onto OS threads.
G (Goroutine): Represents a single unit of work. Contains its own stack (starts at 2KB, grows dynamically), program counter, and state (runnable, running, waiting, syscall).
M (Machine): An OS thread created by the runtime. M threads actually execute goroutine code. The Go runtime limits the number of M threads (default max 10,000).
P (Processor): A logical processor that holds a local run queue of goroutines. The number of P processors is set by GOMAXPROCS (defaults to number of CPU cores).
How scheduling works:
1// Check and set GOMAXPROCS2fmt.Println("GOMAXPROCS:", runtime.GOMAXPROCS(0))34// Set to 4 processors for 4-core machine5runtime.GOMAXPROCS(4)67// Goroutine scheduling8runtime.Gosched() // Yield to scheduler
Work stealing: When a P has nothing to do, it randomly selects another P and takes half its goroutines. This prevents idle processors.
When to use GMP knowledge:
runtime.LockOSThread() behaves differently.Common mistakes:
runtime.GOMAXPROCS(0) returns the CURRENT value without changing it.runtime.LockOSThread() without understanding it pins the goroutine to one OS thread.