Goroutines and the Go Runtime#

The Go runtime is far more than a standard library—it embeds garbage collection (GC), channel synchronization, memory management, and a user-space M:N scheduler that multiplexes tens of thousands of lightweight goroutines onto a small pool of operating system threads.


1. The Work Stealing Algorithm#

Go concurrency follows a Fork-Join model, where spawning a goroutine (go func()) represents a Fork, and waiting on a channel receive (<-ch) or sync.WaitGroup (wg.Wait()) represents a Join.

To balance load evenly across CPU cores without central lock contention, the Go scheduler implements a Work Stealing algorithm.

   [ Processor P1 (Busy) ]                [ Processor P2 (Idle) ]
   +---------------------+                +---------------------+
   |  G1 (Oldest / Head) | --(Steal)----> |  G1 (Stolen!)       |
   |  G2                 |                +---------------------+
   |  G3 (Newest / Tail) | <-- P1 pops newest tasks (Tail / runnext) first (LIFO)
   +---------------------+

(1) Deque-Based Local Run Queues & Stealing Rules#

Each logical processor ($P$) owns a double-ended queue (Deque, Local Run Queue) and operates under three core rules:

  1. Fork (Creation): When a running goroutine spawns a new child goroutine (go), the child is pushed onto the Tail (or runnext slot) of the current processor’s deque.
  2. Local Execution (LIFO Bias): When a processor looks for its next goroutine to execute, it pops from the newest end (Tail / runnext) of its own deque first.
  3. Work Stealing (FIFO from Head): When a processor’s own deque becomes completely empty, after checking the Global Run Queue and Netpoller, it randomly selects another busy processor and steals half of the goroutines from the Head (the oldest end) of that processor’s deque.

(2) Why Pop from Tail Locally (LIFO) but Steal from Head Remotely (FIFO)?#

  • Maximizing CPU Cache Locality: A newly forked child goroutine (at the Tail/runnext) very likely operates on data still warm in the parent CPU core’s L1/L2 cache lines. Furthermore, the parent goroutine often immediately reaches a Join point (<-ch) waiting for that exact child’s result. Executing the newest child on the same core immediately minimizes cache misses and context-switching overhead.
  • Minimizing Contention & Stealing Larger Work Trees: Because the owning processor operates on the Tail while a stealing processor takes from the opposite end (Head), atomic/lock contention between the two cores is minimized. Moreover, older goroutines sitting at the Head represent earlier forks higher up in the call tree, meaning they are more likely to spawn further sub-tasks and keep the stealing processor busy longer.

(3) Stealing Continuations (Goroutines) vs. Stealing Tasks#

In traditional thread pools that enqueue bare function pointers (Tasks), whenever a parent task blocks waiting on a child (Join), the underlying OS thread stalls completely unless extra threads are spawned. Go instead schedules and steals Continuations (Goroutines)—each equipped with its own growable call stack and saved instruction pointer (PC). When a goroutine blocks on a channel (Join), the runtime simply parks the goroutine (gopark) off the thread in nanoseconds and immediately switches the OS thread to the next runnable goroutine.


2. The G-M-P Scheduler Architecture#

Go’s runtime orchestrates M:N scheduling on top of physical CPU cores through three primary internal structures (G, M, P):

LayerEntityCreated & Scheduled ByRole & Characteristics
HardwareCPU CorePhysical SiliconExecutes machine instructions from at most 1 OS thread (M) at any given nanosecond.
Kernel LevelM (Machine)Requested by Go runtime via Syscall (clone) -> Scheduled onto cores by OS KernelAn actual OS kernel thread time-sliced by the operating system scheduler (e.g., Linux CFS). Has a fixed heavy stack (~1–2MB).
Runtime ContextP (Processor)Go Runtime (Count equals GOMAXPROCS, e.g., 8 on an 8-core machine)Not a physical CPU core, but a “work desk” (logical resource context) required to execute Go code. Holds the Local Run Queue (LRQ) and thread-local memory cache (mcache).
User SpaceG (Goroutine)Go Runtime (Created in user space on go func())Represents a single goroutine with a dynamic stack (starting at 2KB), instruction/stack pointers (PC, SP), and state (_Grunnable, _Grunning, _Gwaiting, _Gsyscall).

Why Does P Exist Between G and M?#

In early Go (Go 1.0), only G and M existed, forcing all OS threads (M) to contend on a single global mutex-protected run queue and hold bulky per-thread memory caches even when blocked in syscalls. Introducing P solves two fundamental problems:

(1) Zero-Downtime Handoff During Blocking Syscalls#

   [ 1. Normal Execution ]            [ 2. Blocking Syscall Handoff ]
      +---------------+                  +---------------+     +---------------+
      | M1 (Thread 1) |                  | M1 (In Kernel)|     | M2 (Thread 2) |
      +-------+-------+                  +-------+-------+     +-------+-------+
              |                                  |                     | (Handoff!)
      +-------v-------+                  +-------v-------+     +-------v-------+
      | P1 [ G2, G3 ] |                  | G1 (Syscall)  |     | P1 [ G2, G3 ] |
      +-------+-------+                  +---------------+     +-------+-------+
              |                          (No P attached!)              |
      +-------v-------+                                        +-------v-------+
      | G1 (Running)  |                                        | G2 (Running)  |
      +---------------+                                        +---------------+
  1. Suppose OS thread M1 holds logical processor P1 and is executing goroutine G1, when G1 invokes a synchronous blocking OS syscall (e.g., blocking file I/O).
  2. Without a separable P1, the runnable goroutines queued behind it (G2, G3) would be trapped on the blocked M1 thread and starve.
  3. In the G-M-P model, as soon as M1 blocks in the kernel, P1 (along with its Local Run Queue containing G2 and G3) detaches from M1 and immediately hands off to an idle or newly spawned OS thread M2.
  4. During the blocking syscall, G1 belongs to NO P (No P attached!): G1 transitions to _Gsyscall state and remains bound only to M1 inside the kernel waiting for I/O completion, while G2 and G3 continue executing on M2 via P1 with zero interruption.
  5. Once G1’s syscall returns from the kernel, the Go runtime places G1 (_Grunnable) into an available P’s run queue (or the Global Run Queue) to resume execution, and parks M1 in the idle thread pool for future syscalls.

(2) Lock-Free Local Run Queues & Memory Caching (mcache)#

  • Because each P is owned by at most one active M at any instant, the running thread can allocate small objects from P’s per-processor heap cache (mcache) and pop runnable Gs from P’s Local Run Queue without acquiring global locks.

3. Physical CPU Cores vs. M (OS Threads): How P Prevents Thread Thrashing#

(1) Who Creates OS Threads (M) and Who Assigns Them to CPU Cores?#

The responsibilities for creating an OS thread and scheduling it onto a physical CPU core are strictly separated:

  1. Thread Creation Request (User Space -> System Call -> Kernel): The Go runtime (in user space) does not pre-allocate hundreds of OS threads. Only when existing Ms become blocked in syscalls and a P needs a worker thread does the Go runtime invoke a system call (clone() on Linux or pthread_create()) asking the OS kernel to create a new M.
  2. CPU Core Assignment (100% OS Kernel Scheduler): Once created, deciding which physical CPU core runs a given M and time-slicing multiple active threads across cores is handled 100% by the OS kernel scheduler (e.g., Linux CFS).

(2) Can the Number of Ms Exceed the Number of CPU Cores?#

  • How many Ms can 1 CPU core execute at the exact same nanosecond? Strictly 1 (or 1 per logical hardware thread with Hyper-Threading). On an 8-core CPU, at most 8 Ms can physically execute instructions simultaneously.
  • How many Ms can exist in the process simultaneously? Far more than 8. If 100 goroutines invoke synchronous blocking disk reads (read() syscall) at the same time, 100 Ms will block inside the kernel waiting for disk I/O, while 8 additional Ms hold the 8 Ps (GOMAXPROCS=8) to continue running other goroutines—resulting in 108 total OS threads (M). By default, Go allows up to 10,000 OS threads (M) before panicking (configurable via debug.SetMaxThreads).

(3) How the “8 Desks (P)” Invariant Prevents OS Context-Switch Thrashing#

If all 108 OS threads (M) tried to actively run Go code at the same time on an 8-core CPU, the OS kernel would be forced to constantly context-switch 108 threads across 8 cores, crippling performance via OS thread context-switch thrashing.

P (GOMAXPROCS) acts as the strict concurrency gatekeeper that prevents this:

   [ Physical CPU Cores (8 Cores) ]
     Core1   Core2   Core3  ...  Core8   <-- OS Kernel maps 8 active Ms 1:1 to cores
       ^       ^       ^           ^
       |       |       |    ...    |
   +-------+-------+-------+---+-------+
   |  P1   |  P2   |  P3   |...|  P8   | <-- GOMAXPROCS = 8 ("8 Work Desks")
   | (M1)  | (M2)  | (M3)  |...| (M8)  | <-- Only the 8 Ms holding a P run Go code!
   +-------+-------+-------+---+-------+
   -------------------------------------------------------------------------
   [ Remaining 100 OS Threads without P (M9 ~ M108) ]
   * Blocked in Kernel (waiting on Syscall I/O) OR Parked in Idle Pool
   * CPU Usage = 0% (Completely excluded from OS context-switch contention!)
  • Because an M must hold one of the GOMAXPROCS (8) P contexts in order to execute Go code, at most 8 Ms are ever actively competing for CPU time to run Go code—regardless of whether 100 or 1,000 other Ms are asleep waiting on syscalls.
  • This preserves an ideal 1:1 mapping between active Go worker threads (M+P) and physical CPU cores, virtually eliminating OS-level thread switching overhead.

4. User-Space Context Switching & 10ms Preemptive Time-Slicing (sysmon)#

(1) Normal Goroutine Switches Never Enter the OS Kernel (~100ns vs ~1–2µs)#

When goroutine G1 parks on a channel (<-ch), mutex, or network socket (netpoller) and the runtime switches to G2 on the same M, the OS kernel is completely unaware that a switch occurred.

  • OS Thread Switch (M1 <-> M2, ~1–2µs): Requires trapping from User Mode (Ring 3) into Kernel Mode (Ring 0), saving full CPU register state, and often invalidating virtual memory address caches (TLB).
  • Goroutine Switch (G1 <-> G2, ~100–200ns): The OS thread (M1) stays running on the CPU core in 100% User Space. Go’s runtime assembly (runtime.gogo / runtime.mcall) simply swaps the CPU’s Instruction Pointer (PC / RIP) and Stack Pointer (SP / RSP) from G1’s stack to G2’s stack—roughly 10x faster than an OS thread switch.

(2) What If a Goroutine Runs an Infinite CPU Loop? (sysmon & 10ms Preemption)#

If goroutine switching happens in user space without the OS kernel, what stops a CPU-bound goroutine (G1) that performs no channel I/O or syscalls from monopolizing P1 forever and starving G2?

// Pure CPU loop with no channel operations or blocking syscalls
for {
    sum += 1
}

To prevent starvation, the Go runtime implements its own user-space preemptive time-slicing (10ms quantum):

   +-------------------------------------------------------+
   | sysmon (Background Monitor Thread M - Runs without P) |
   | * Scans all P and G every 20us ~ 10ms                 |
   | * Detects: "G1 has held P1 for > 10ms continuously!"  |
   +---------------------------+---------------------------+
                               |
                               v  (Sets stackPreempt OR sends SIGURG signal)
   +---------------------------+---------------------------+
   | G1 running on M1 + P1                                 |
   +---------------------------+---------------------------+
                               |
                               +--> 1. Preempts G1 -> Pushes G1 to Global Run Queue
                               +--> 2. Schedules G2 from P1 Local Run Queue onto CPU!
  1. The sysmon Background Daemon (10ms Time Slice): At startup, the Go runtime launches a dedicated background OS thread called sysmon that runs without needing a P. It periodically inspects all Ps (20µs to 10ms interval). Whenever it detects that a goroutine has been running continuously for more than 10ms, it triggers preemption.
  2. Phase 1 — Cooperative Stack-Guard Preemption (Pre-Go 1.14 & Function Calls):
    • The Go compiler automatically inserts a tiny stack-bound check into every function prologue.
    • sysmon sets G1’s stack guard field to stackPreempt. The next time G1 calls any function, the stack check triggers and gracefully yields the processor to the scheduler.
  3. Phase 2 — Asynchronous Signal Preemption via SIGURG (Go 1.14+):
    • If G1 is stuck in a tight for loop that never makes a function call, the function prologue check would never fire.
    • Since Go 1.14, sysmon sends an OS signal (SIGURG) directly to the OS thread (M1) running G1.
    • When M1 receives SIGURG, Go’s registered signal handler immediately interrupts G1 mid-loop, saves its CPU registers onto its stack, moves G1 to the Global Run Queue, and switches P1 to execute the next waiting goroutine (G2).

By combining 100% user-space switching (~100ns) for normal I/O and channel operations with 10ms sysmon + SIGURG preemption for CPU-bound loops, Go achieves both nanosecond-level coroutine efficiency and fair preemptive multitasking.