Sobes.tech
Senior

How does the Go scheduler work? Tell about the GMP model.

sobes.tech AI

Answer from AI

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

  • G (goroutine) — a lightweight thread of execution.
  • M (machine) — an OS system thread on which goroutines run.
  • P (processor) — a logical processor that connects G and M.

Each M can execute only one G at a time, but to execute, M must have access to P. The number of P limits the maximum number of goroutines that can run simultaneously at the scheduler level.

Scheduler operation:

  1. Goroutines are created and placed in the ready queue.
  2. P selects a G from the queue and associates it with an M.
  3. M executes G.
  4. If G blocks (e.g., on I/O), M is released and can take another G.
  5. The scheduler balances the load between M and G, switching them as needed.

This approach allows efficient use of system threads and scaling the execution of a large number of goroutines with minimal overhead.