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/ # Channel {{< katex />}} While the `sync` package operates by **synchronizing by sharing memory**, channels embody the CSP (Communicating Sequential Processes) philosophy of **sharing memory by communicating**. Rather than guarding shared memory with locks, goroutines pass data safely through channel conduits to achieve synchronization. ## 1. Core Properties & Unidirectional Channels (Directionality) Each value written to a channel can be **read only once (Single Read)**. To enforce design intent and prevent misuse at compile time, Go's type system provides **unidirectional channels**: - **Bidirectional Channel:** `chan T` (supports both sending and receiving) - **Receive-only Channel:** `<-chan T` (can only read values from the channel) - **Send-only Channel:** `chan<- T` (can only write values to the channel) ```go func process(in <-chan int, out chan<- int) { val := <-in // OK: Read from receive-only channel // in <- 10 // Compile error: cannot send to receive-only channel out <- val * 2 // OK: Write to send-only channel // <-out // Compile error: cannot receive from send-only channel } ``` A bidirectional channel is **implicitly converted** into a unidirectional channel when passed as a function argument or returned from a function. This guarantees that consumers cannot erroneously write to or close channels intended strictly for receiving. --- ## 2. Closing a Channel & 1:N Broadcast Pattern Closing a channel (`close(ch)`) is a communication signal indicating to downstream goroutines that no further data will be sent. ### The Comma-ok Idiom & Zero Values Reading from a closed channel never blocks; it always completes immediately: - If buffered values remain, they are retrieved in strict FIFO order. - If the buffer is completely empty, the read produces the type's **Zero Value** and sets the boolean flag to **`false`**. ```go val, ok := <-ch if !ok { fmt.Println("Channel closed and buffer drained.") } ``` ### Automatic Termination with `for-range` A `for-range` loop blocks waiting for incoming data. When the channel is closed and all remaining buffered items are consumed, it **automatically exits the loop**: ```go for val := range ch { fmt.Println("Processing:", val) } // Execution proceeds here cleanly once ch is closed ``` ### 1:N Simultaneous Unblocking (Broadcast Pattern) Because reads on a closed channel succeed indefinitely (returning zero values), closing a channel provides an elegant mechanism to **signal multiple goroutines simultaneously**—serving as a channel-native replacement for `sync.Cond.Broadcast()`. Rather than sending $N$ values into a channel, a single call to `close()` unblocks all waiting goroutines at once: ```go begin := make(chan struct{}) var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(1) go func(id int) { defer wg.Done() <-begin // Blocks consuming 0% CPU until the channel closes fmt.Printf("Worker %d started\n", id) }(i) } fmt.Println("Broadcasting start signal to all goroutines...") close(begin) // Single close unblocks all 5 goroutines simultaneously wg.Wait() ``` --- ## 3. Buffered Channels & Runtime Optimization An unbuffered channel is functionally defined as a buffered channel with zero capacity (`make(chan T, 0)`). A buffered channel (`make(chan T, N)`) allocates a fixed-capacity FIFO circular ring buffer in memory. - `len(ch)`: Number of elements currently queued in the buffer - `cap(ch)`: Maximum capacity of the buffer ($N$) ### Direct Stack-to-Stack Copy Optimization If a receiver goroutine is already blocked waiting on an empty channel when a sender arrives, the Go runtime optimizes the transfer: it bypasses the ring buffer entirely and **copies the data directly from the sender goroutine's stack to the receiver's stack**, immediately waking the receiver. ### Premature Optimization & Hidden Deadlocks Katherine Cox-Buday cautions against introducing buffered channels indiscriminately: 1. **Masking Deadlocks:** A program with an architectural deadlock may appear functional during tests simply because the buffer accommodates the unhandled writes. When production workloads fill the buffer, the deadlock detonates under pressure. 2. **Producer-Consumer Mismatch:** A buffer only cushions temporary burst rate differences; it cannot resolve structural throughput deficits between producers and consumers. Increasing buffer sizes without rigorous profiling is classic premature optimization. --- ## 4. Channel State Matrix The entire runtime behavior, panic triggers, and blocking semantics of Go channels are summarized in the 3x3 state matrix (Table 3-2 in *Concurrency in Go*): | Operation | `nil` Channel | Open Channel | Closed Channel | | :--- | :--- | :--- | :--- | | **Read (`<-ch`)** | **Permanent Block** | Value if present; blocks if empty | Remaining buffer, then **Zero Value, false** (Never blocks) | | **Write (`ch <- x`)** | **Permanent Block** | Success if capacity exists; blocks if full | **panic!** (send on closed channel) | | **Close (`close(ch)`)** | **panic!** (close of nil channel) | Successfully transitions to Closed | **panic!** (close of closed channel) | ### The 3 Panic Conditions 1. Closing a `nil` channel (`close(nil)`) 2. Closing an already closed channel (double close) 3. Writing to a closed channel (`ch <- data`) ### The 2 Permanent Blocking Conditions & Disabling Select Cases Reads and writes on a `nil` channel do not panic; they block permanently. This is a deliberate language feature designed to **dynamically disable cases in a `select` statement**. If a closed channel is left as-is, reading from it never blocks and repeatedly yields Zero Values with `false`. This causes a `select` loop to spin at 100% CPU in an infinite busy-loop. Assigning `nil` to the channel variable permanently silences that branch, allowing the loop to cleanly wait only on remaining active channels: ```go // Dynamically disable select branches when channels close by assigning nil for a != nil || b != nil { select { case val, ok := <-a: if !ok { a = nil // Disables case <-a from select evaluation continue } fmt.Println("From A:", val) case val, ok := <-b: if !ok { b = nil // Disables case <-b from select evaluation continue } fmt.Println("From B:", val) } } ``` --- ## 5. Channel Ownership Pattern To systematically eliminate all panics and deadlocks, Katherine Cox-Buday outlines the **Channel Ownership Pattern** as the gold-standard architectural model. ### Responsibility Separation: Owner vs. Consumer - **Channel Owner (Producer Goroutine):** 1. Instantiates the channel (`make`). -> *Eliminates nil channel panics* 2. Performs writes. 3. Closes the channel (`close`). -> *Eliminates double-close and write-to-closed panics* 4. Encapsulates the above in a function and exposes only a **receive-only channel (`<-chan T`)**. - **Channel Consumer:** - Receives only a read-only channel; cannot write or close. - Handles blocking reads and reacts gracefully to channel closure (`for-range` or `ok == false`). ```go // chanOwner encapsulates lifecycle and returns a receive-only channel. chanOwner := func() <-chan int { resultStream := make(chan int, 5) // 1. Instantiate go func() { defer close(resultStream) // 3. Close for i := 1; i <= 5; i++ { resultStream <- i // 2. Write } }() return resultStream // 4. Expose as receive-only channel } // Consumer resultStream := chanOwner() for result := range resultStream { // Consumer handles blocking and termination fmt.Println("Received:", result) } fmt.Println("Done receiving!") ``` ### Closing Channels with Multiple Producers When multiple producers write to a single channel, having any producer call `close()` triggers a double-close panic or write-on-closed panic. The idiomatic Go solution is to **monitor all producers with `sync.WaitGroup` and close the channel exactly once from a separate coordinator goroutine**: ```go ch := make(chan int) var wg sync.WaitGroup for i := 1; i <= 3; i++ { wg.Add(1) go func(workerID int) { defer wg.Done() for j := 1; j <= 2; j++ { ch <- workerID*10 + j } }(i) } // Coordinator goroutine closes the channel once all producers terminate go func() { wg.Wait() close(ch) }() for val := range ch { fmt.Println("Processed:", val) } ``` --- ## Under the Hood & Performance ### What a Channel Actually Is: `hchan` Struct In Go, a channel is not a magical low-level primitive, but a high-level construct implemented as the **`hchan` struct** in the Go runtime (`src/runtime/chan.go`): ```go type hchan struct { qcount uint // Total data in the buffer dataqsiz uint // Buffer capacity buf unsafe.Pointer // Circular queue buffer sendx uint // Send index recvx uint // Receive index recvq waitq // List of waiting receivers sendq waitq // List of waiting senders lock mutex // Internal Mutex guarding the channel } ``` A channel is essentially an elegant wrapper combining a **circular buffer + waiting goroutine queues + an internal Mutex**. ### Primitives vs Higher-Level Synchronization The official Go documentation for `package sync` explicitly notes: > *"Package sync provides basic synchronization primitives such as mutual exclusion locks... Higher-level synchronization is better done via channels and communication."* - **`sync.Mutex` / `atomic` (Primitives):** The lowest-level, indivisible hardware/OS building blocks. - **`Channel` (High-Level):** A first-class citizen designed on top of these primitives for message-passing concurrency. ### Why `sync.Mutex` Is Recommended for Performance-Critical Sections In the [Concurrency Decision Tree](/programming/go/concurrency/csp/#4-gos-philosophy-and-decision-tree-channel-vs-mutex), Katherine Cox-Buday recommends using primitives for performance-critical sections for a concrete mechanical reason: 1. Every channel send/receive incurs internal mutex locking, buffer copies, and goroutine parking/unparking via the Go scheduler. 2. Because **a channel internally uses a Mutex, it cannot be faster than a Mutex alone.** 3. For ultra-short, high-frequency critical sections (such as simple counter increments or in-memory map updates), using **`sync.Mutex` or `sync/atomic` directly is orders of magnitude faster and lighter** than routing data through the channel machinery.