Go's M:N Scheduler: Multiplexing Millions on Few OS Threads

Go's runtime employs an M:N scheduling model, efficiently mapping many (M) goroutines onto a smaller number (N) of OS threads, managing them in user space to reduce overhead and maximize CPU utilization by switching tasks on the same OS thread during I/O waits.

The top 3

  1. M:N vs. 1:1 vs. N:1: Go's Concurrency Edge: Go's M:N scheduler (multiplexing many Goroutines onto fewer OS threads) strikes a balance between traditional 1:1 models (like Java/C++ threads, which incur high memory and context-switching overhead) and N:1 models (user-level threads unable to utilize multiple CPU cores). This hybrid approach enables superior scalability and efficient non-blocking I/O.
  2. Go Scheduler's P-M-G Model: Core Mechanics: Go's M:N scheduler operates using the G-M-P model: Goroutines (G) are the lightweight units of execution; OS Threads (M) execute Gs; and Processors (P) are logical schedulers, each holding a local queue of runnable Gs. Ps distribute Gs to Ms, ensuring efficient CPU utilization. A key mechanism is 'work-stealing,' where an idle M associated with a P can 'steal' Gs from other P's local queues to maintain load balance and prevent CPU idle time.
  3. Goroutines' Minimal Overhead: Enabling Mass Concurrency: Each Go goroutine is extremely lightweight, typically starting with only 2KB of stack memory, which can dynamically grow or shrink. This is significantly less than the several megabytes often required for traditional OS threads, allowing Go to efficiently manage thousands or even millions of concurrent tasks with minimal memory footprint.

Sources

Open the full topic