Sobes.tech
Senior

How does the goroutine scheduler work in Go (GMP model)? What is M in the GMP model?

sobes.tech AI

Answer from AI

The goroutine scheduler in Go is based on the GMP model, where:

  • G (Goroutine) — a lightweight thread of execution.
  • M (Machine) — an OS thread that executes goroutines.
  • P (Processor) — a logical processor that connects G and M, managing execution.

M is the actual OS thread that runs the goroutine code. To start a goroutine, a P is needed, which allocates an M to execute G. The number of P's is limited (by default equal to the number of CPUs), which allows controlling parallelism.

Workflow:

  1. A goroutine (G) is assigned to a P.
  2. P is linked to an M (an OS thread), which executes G.
  3. When a goroutine blocks (e.g., on I/O), M is released and can run another goroutine.
  4. The scheduler switches goroutines between M's via P, ensuring concurrency and parallelism.

Thus, M is a real OS thread executing goroutines, while P is an abstraction managing the distribution of goroutines across threads.

How does the goroutine scheduler work in Go (GMP… - sobes.tech