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/ # Select If channels are the glue that binds independent goroutines together, the `select` statement is **the glue that binds channels together to compose larger program abstractions**. Much like the `select(2)` system call in network programming multiplexes multiple file descriptors, Go's `select` is a first-class language primitive that coordinates and synchronizes multiple communication operations simultaneously. --- ## 1. Channel Multiplexing and Blocking A `select` statement simultaneously evaluates the readiness of channel send and receive operations across multiple cases: ```go var c1, c2 <-chan int var c3 chan<- int select { case v := <-c1: fmt.Println("Read from c1:", v) case v := <-c2: fmt.Println("Read from c2:", v) case c3 <- 10: fmt.Println("Wrote 10 to c3") } ``` - Whichever channel becomes **ready to communicate first** executes its corresponding block. - If none of the channels are ready, the current goroutine suspends (consuming 0% CPU) in a **blocked** state until one becomes active. --- ## 2. Pseudo-Random Uniform Selection If multiple channels are **simultaneously ready**, does Go evaluate cases sequentially from top to bottom? **No. The Go runtime performs a pseudo-random uniform selection over all ready cases.** Katherine Cox-Buday's benchmark experiment (*Concurrency in Go*, p. 118): ```go c1 := make(chan interface{}); close(c1) c2 := make(chan interface{}); close(c2) var c1Count, c2Count int for i := 0; i < 1000; i++ { select { case <-c1: c1Count++ case <-c2: c2Count++ } } fmt.Printf("c1Count: %d, c2Count: %d\n", c1Count, c2Count) // Sample output: c1Count: 505, c2Count: 496 (~50:50 uniform distribution) ``` ### Rationale Behind Random Selection 1. **Preventing Starvation:** If evaluated sequentially (like C `select`), channels declared at the top under heavy traffic would perpetually starve lower-order cases from ever executing. 2. **Optimal Average-Case Performance:** The Go runtime cannot infer developer business logic or priority intentions. Assigning equal probability weights to all ready cases ensures fair scheduling and consistent, robust performance across all Go programs in the average case. --- ## 3. Priority `select` Pattern Because Go selects cases uniformly at random, a practical dilemma arises: **"How can we strictly prioritize one channel (e.g., an urgent cancellation signal) over normal data channels?"** Placing both channels side-by-side in a single `select` yields a 50:50 random distribution, which can delay urgent signals. ### Solution: Pre-emption Pattern via Nested `select` with `default` ```go for { // Stage 1: Non-blocking check for urgent signals select { case <-urgentChan: fmt.Println("Processing urgent task with highest priority") return default: // Fall through immediately if urgentChan is empty } // Stage 2: Wait on both channels only when urgentChan was initially empty select { case <-urgentChan: fmt.Println("Received urgent task while waiting") return case data := <-normalChan: fmt.Println("Processing normal data:", data) } } ``` - **Stage 1:** If data is already queued in `urgentChan`, it is consumed with 100% certainty. If empty, execution immediately falls through to `default:` without blocking. - **Why `case <-urgentChan` must be repeated in Stage 2:** If Stage 2 only waited on `normalChan`, a subsequent urgent signal arriving while waiting would be ignored until `normalChan` unblocked. Repeating `case <-urgentChan` in Stage 2 ensures the goroutine wakes up immediately if an urgent signal arrives while both were idle. --- ## 4. The `default` Clause & Non-blocking Communication The `default:` clause executes immediately without blocking whenever **no channels in any of the cases are ready to communicate**. ### Pitfalls in Polling Loops (Avoiding Busy-Waiting) Placing an unthrottled `default:` clause inside a `for-select` loop is an anti-pattern: ```go // Anti-pattern: Spins at 100% CPU in a tight busy-loop for { select { case data := <-ch: process(data) default: // Executes repeatedly whenever ch is empty, pegging CPU! } } ``` ### Idiomatic Real-World Pattern: Polling Cancellation Signals `default:` is properly used when performing background work while intermittently polling for cancellation: ```go done := make(chan struct{}) // (Background goroutine calls close(done) after a delay) workCounter := 0 loop: for { select { case <-done: break loop // Exit immediately when signalled default: // Progress background work when no signal is present workCounter++ time.Sleep(1 * time.Second) // Throttles CPU consumption } } fmt.Printf("Completed %d work cycles before termination\n", workCounter) ``` --- ## 5. Timeouts & Special Cases ### 1) Concise Timeouts via `time.After` To prevent indefinite blocking when waiting for a response, multiplex the operation with `time.After`: ```go select { case res := <-responseChan: fmt.Println("Received result:", res) case <-time.After(1 * time.Second): fmt.Println("Timed out after 1 second, aborting operation") } ``` ### 2) `select {}` (Empty Select) A `select {}` statement with no cases blocks the current goroutine permanently (consuming 0% CPU). It is commonly used to prevent the main goroutine from exiting while background daemons run. ### 3) Dynamic Case Disabling via `nil` Channels Reads and writes on a `nil` channel block permanently. When managing multiple streams, assigning `ch = nil` upon channel closure removes that branch from `select` evaluation, preventing busy-loops on closed channels. --- ## 6. The `runtime.GOMAXPROCS` Lever Introduced at the end of Chapter 3, `GOMAXPROCS` is a key tuning lever for the Go runtime scheduler: - **True Nature:** It does not dictate physical CPU cores; rather, it controls the **number of operating system threads (M) hosting work queues** that can execute goroutines simultaneously. - **Default Evolution:** Prior to Go 1.5, the default was 1. Since Go 1.5, it is automatically set to match the host machine's logical CPUs (`runtime.NumCPU()`). - **Best Practice:** Leave the default untouched in production. However, during testing, **temporarily setting `GOMAXPROCS` significantly higher than CPU cores** intentionally magnifies goroutine interleaving, accelerating the detection and diagnosis of elusive race conditions.