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/ # CSP (Communicating Sequential Processes) and Channels One of the most transformative paradigms in concurrent programming originated in 1978 with C.A.R. Hoare's landmark paper, **"Communicating Sequential Processes (CSP)"**. Go adopted CSP theory as a first-class citizen in the language design, shaping today's **Goroutines** and **Channels**. --- ## 1. What Is CSP? In the late 1970s, computer science was intensely focused on structured programming (eliminating `goto`) and object-oriented paradigms. Concurrency was rarely treated as a fundamental construct; most concurrency relied on **shared memory with lock synchronization**. Hoare challenged this status quo: > *"Input and output are basic primitives of programming that have been overlooked, particularly in concurrent code. Rather than having processes fight over shared memory, **processes should communicate exclusively via input and output commands.**"* ### Core Principles of Hoare's CSP 1. **Sequential Processes:** Each process is an encapsulated unit of logic with its own independent state running sequentially. 2. **Synchronous Message Passing:** Inter-process interaction occurs via explicit input and output operations, not shared variables. 3. **Handshake:** Communication occurs only when both sender and receiver meet, inherently synchronizing execution. --- ## 2. Hoare's Notation and Go Channels The formal notation defined in Hoare's 1978 paper was directly realized in Go syntax over three decades later: | CSP Notation (Hoare, 1978) | Go Implementation | Description | | :--- | :--- | :--- | | `process ! value` | `ch <- value` | Send data to process/channel (Output command) | | `process ? variable` | `variable := <-ch` | Receive data from process/channel (Input command) | | `*[west?c -> east!c]` | `for c := range west { east <- c }` | Pipeline composition between processes | | Guarded Commands (`->`) | `select { case ... }` | Wait across multiple channels and execute ready communication | Hoare incorporated Edsger Dijkstra's **Guarded Commands** so communication only triggers when conditions are satisfied, which became Go's **`select` statement**. --- ## 3. Shared Memory vs CSP Model | Dimension | Shared Memory Model | CSP Model (Message Passing) | | :--- | :--- | :--- | | **Primitives** | `sync.Mutex`, `Semaphore`, Condition Variables | `chan` (Channel), `select` | | **Communication** | Read/write to identical memory addresses | Transfer independent data values/ownership via channels | | **Synchronization** | Manual Lock/Unlock conventions | Inherent blocking synchronization on send/receive | | **Key Risks** | Data Races, Deadlocks, Race Conditions | Goroutine Leaks | | **Composability** | Low (nesting multiple locks causes deadlocks) | **Very High** (pipelines, timeouts, cancellations compose naturally) | --- ## 4. Go's Philosophy and Decision Tree: Channel vs Mutex The famous Go adage directly reflects Hoare's CSP philosophy: > **"Do not communicate by sharing memory; instead, share memory by communicating."** Why then does Go also provide `sync.Mutex` in its standard library? In practice, dogmatically using only channels or only mutexes is an antipattern. In *Concurrency in Go*, Katherine Cox-Buday provides a clear **Decision Tree**: {{< mermaid >}} graph TD Q1["Is it a performance critical section?"] Q2["Are you trying to transfer ownership of data?"] Q3["Are you trying to guard internal state of a struct?"] Q4["Are you trying to coordinate multiple pieces of logic?"] P["Use Primitives
(sync.Mutex, atomic, etc.)"] C["Use Channels"] Q1 -- Yes --> P Q1 -- No --> Q2 Q2 -- Yes --> C Q2 -- No --> Q3 Q3 -- Yes --> P Q3 -- No --> Q4 Q4 -- Yes --> C Q4 -- No --> P {{< /mermaid >}} ### When to Use Channels 1. **Transferring Ownership:** When a producer generates data and hands it to a consumer. Once sent onto the channel, the producer no longer touches that data, eliminating data races. 2. **Coordination & Composition:** When assembling complex asynchronous workflows like timeouts, context cancellations, or fan-in/fan-out pipelines. ### When to Use sync.Mutex 1. **Guarding Internal State:** When protecting internal struct fields (e.g., caches, maps, counters). Encapsulating a `mu sync.Mutex` inside the struct is much simpler and more idiomatic than spawning background goroutines and channels. 2. **Performance-Critical Sections:** Channels incur runtime overhead (buffer queues, lock management, scheduling). For simple counter increments or high-frequency memory updates, `sync.Mutex` or `sync/atomic` is substantially faster. --- ## Summary * **CSP** was formulated in 1978 by C.A.R. Hoare, establishing **explicit input/output communication** as the fundamental primitive of concurrency rather than shared memory. * Go adopted CSP's communication and guarded commands via **Channels** and **`select`**, radically simplifying concurrent program structure. * **Practical Selection:** Use **Channels** for ownership transfer and workflow coordination; use **Mutexes** for internal state encapsulation and microsecond performance-critical sections.