Cheat Sheet - Linux: /linux/ - CLI: /linux/cli/ - locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /linux/cli/make/ - awk: /linux/cli/awk/ - find: /linux/cli/find/ - grep: /linux/cli/grep/ - pgrep: /linux/cli/pgrep/ - ps: /linux/cli/ps/ - pstree: /linux/cli/pstree/ - trap: /linux/cli/trap/ - xargs: /linux/cli/xargs/ - Shell: /linux/shell/ - BASH_SOURCE: /linux/shell/bash-source/ - Redirection: /linux/shell/redirection/ - Special Variables: /linux/shell/special-variables/ - Scripting Tips: /linux/shell/script-tips/ - set -o vi: /linux/shell/bash-vi-mode/ - Shell Processing Order: /linux/shell/process-order/ - What are Interactive and Login Shells?: /linux/shell/interactive-login/ - Double Quote Expansion: /linux/shell/shell-expansion/ - System Programming: /linux/system-programming/ - File I/O: /linux/system-programming/file-io/ - Process: /linux/system-programming/process/ - Shared Libraries: /linux/system-programming/shared-libraries/ - Kernel: /linux/kernel/ - Go: /programming/go/ - Concurrency: /programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/ - Channel: /programming/go/concurrency/channel/ - Select: /programming/go/concurrency/select/ - sync: /programming/go/concurrency/sync/ - Concurrency Patterns: /programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /programming/go/concurrency/runtime/ - Standard Library: /programming/go/std/ - os: /programming/go/std/os/ - context: /programming/go/std/context/ - io: /programming/go/std/io/ - json: /programming/go/std/json/ - net/http: /programming/go/std/net-http/ - slog: /programming/go/std/slog/ - testing: /programming/go/std/testing/ - time: /programming/go/std/time/ - Ellipsis (...): /programming/go/ellipsis/ - error: /programming/go/error/ - Function: /programming/go/function/ - Go Tool: /programming/go/tool/ - Interface: /programming/go/interface/ - Map: /programming/go/map/ - Package and Module: /programming/go/package-module/ - Pointer: /programming/go/pointer/ - Slice: /programming/go/slice/ - String: /programming/go/string/ - Switch: /programming/go/switch/ - Comparison: /programming/go/comparison/ - defaultdict: /programming/python/collections/defaultdict/ - heapq: /programming/python/collections/heapq/ - @cache: /programming/python/cache/ - abc: /programming/python/abc/ - bisect: /programming/python/bisect/ - Type Hints: /programming/python/type-hints/ - Passing Mechanism: /programming/python/passing-mechanism/ - uv: /programming/python/uv/ - *args and **kwargs: /programming/python/args-kwargs/ - re: /programming/python/re/ - C: /programming/c/ - Pointers and Arrays: /programming/c/pointer/ - Syntax Basics: /programming/c/syntax-basics/ - static: /programming/c/static/ - Bit Manipulation: /programming/c/bit-manipulation/ - C vs C++: /programming/c/c-vs-cpp/ - stdatomic: /programming/c/stdatomic/ - C++: /programming/cpp/ - RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/ - Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /programming/cpp/keywords/ - C++ Primer: /programming/cpp/primer/ - Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/ - Expressions: /programming/cpp/primer/expressions/ - Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/ - Statements: /programming/cpp/primer/statements/ - Functions: /programming/cpp/primer/functions/ - Classes: /programming/cpp/primer/classes/ - The IO Library: /programming/cpp/primer/io-library/ - STL: /programming/cpp/primer/stl/ - Lambda Expressions: /programming/cpp/primer/lambda/ - Smart Pointers: /programming/cpp/primer/smart-pointers/ - Copy Control: /programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /programming/cpp/primer/oop/ - Templates and Generic Programming: /programming/cpp/primer/templates/ - Namespaces: /programming/cpp/primer/namespaces/ - Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/ - Advanced: /programming/cpp/advanced/ - Error Handling: /programming/cpp/advanced/error-handling/ - Concurrency & Threading: /programming/cpp/advanced/concurrency/ - Unit Testing: /programming/cpp/advanced/unit-testing/ - Comparison: /programming/comparison/ - Kubernetes: /cloud-devops/kubernetes/ - Fleet: /cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /cloud-devops/kubernetes/api-extension/ - Concept: /cloud-devops/kubernetes/kueue/concept/ - DRA: /cloud-devops/kubernetes/dra/ - Secret Manager: /cloud-devops/terraform/google-secret-manager/ - Knowledge: /network/knowledge/ - PDU: /network/knowledge/osi-model/ - curl: /network/cli/curl/ - Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /cs/regular-expression/ - Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /ai-ml/gpu/driver-and-runtime/ - Serving: /ai-ml/serving/ - Dotfiles: /dotfiles/ - Git: /dotfiles/git/ - Cheat Sheet: /dotfiles/git/cheat-sheet/ - revisions: /dotfiles/git/revisions/ - Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/ - rebase: /dotfiles/git/rebase/ - Branching and Merging: /dotfiles/git/branching-merging/ - Vim: /dotfiles/vim/ - Plugin: /dotfiles/vim/plugin/ - auto-pairs: /dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /dotfiles/vim/plugin/vim-surround/ - Marks: /dotfiles/vim/tips/marks/ - vimrc: /dotfiles/vim/vimrc/ - lf: /dotfiles/lf/ # Goroutines and the Go Runtime {{< katex />}} 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. ```text [ 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**): | Layer | Entity | Created & Scheduled By | Role & Characteristics | | :--- | :--- | :--- | :--- | | **Hardware** | **CPU Core** | Physical Silicon | Executes machine instructions from **at most 1 OS thread (`M`)** at any given nanosecond. | | **Kernel Level** | **`M` (Machine)** | Requested by Go runtime via **Syscall (`clone`)** -> Scheduled onto cores by **OS Kernel** | An actual **OS kernel thread** time-sliced by the operating system scheduler (e.g., Linux CFS). Has a fixed heavy stack (`~1–2MB`). | | **Runtime Context** | **`P` (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 Space** | **`G` (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 ```text [ 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 `G`s 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 `M`s 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 `M`s Exceed the Number of CPU Cores? * **How many `M`s 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 `M`s** can physically execute instructions simultaneously. * **How many `M`s 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 `M`s will block inside the kernel waiting for disk I/O, while 8 additional `M`s hold the 8 `P`s (`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: ```text [ 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 `M`s are ever actively competing for CPU time to run Go code—regardless of whether 100 or 1,000 other `M`s 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`? ```go // 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)**: ```text +-------------------------------------------------------+ | 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 `P`s (`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.