Go 运行时包含一个调度器,它将许多 goroutine 多路复用到少量的 OS 线程上。这种 M:N 调度(M 个 goroutine 在 N 个 OS 线程上)正是使 goroutine 成本极低且 Go 并发如此可扩展的原因。理解它可以解释 goroutine 的性能。
G-M-P 模型
G (Goroutine) — your concurrent task (lightweight, ~2KB stack to start)
M (Machine) — an OS thread (the actual thread the OS schedules)
P (Processor) — a logical processor / scheduling context; holds a queue of runnable Gs
(the number of P's = GOMAXPROCS, default = number of CPU cores)
The scheduler runs G's on M's, coordinated through P's:
Each P has a local run queue of goroutines; an M must hold a P to run G's.
