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/ # `sync` Go's `sync` package is based on **synchronizing by sharing memory**, providing low-level primitives for memory-access synchronization and critical section protection among goroutines. Unlike channels, which share memory by communicating, `sync` deals with traditional locking and signaling primitives. --- ## 1. `sync.WaitGroup` Used to establish a **Join Point** waiting for the completion of concurrent branches in Go's [Fork-Join model]({{< relref "/cs/concurrency-and-parallelism/concepts.md#51-dimension-1-rendezvous-vs-fork-join-lifecycle--synchronization" >}}). For single goroutine cancellation or waiting, [context cancellation]({{< relref "/programming/go/std/context.md" >}}) is preferred, but `WaitGroup` is the standard tool for waiting on multiple concurrent tasks. - `.Add(delta int)`: Adds delta to the internal counter. - `.Done()`: Decrements the counter by 1. Always invoke via `defer` to ensure execution even during panics. - `.Wait()`: Blocks the calling goroutine until the counter drops to zero. ### Fork-Join Example ```go func main() { var wg sync.WaitGroup urls := []string{"https://golang.org", "https://google.com", "https://github.com"} for _, url := range urls { // 1. wg.Add must be called in the parent goroutine before launching wg.Add(1) go func(u string) { defer wg.Done() fetch(u) }(url) // 2. Pass loop variables explicitly as parameters } // Join Point: Block until all goroutines finish wg.Wait() fmt.Println("All fetches completed!") } ``` ### Critical Antipatterns to Avoid 1. **Calling `wg.Add(1)` inside the goroutine:** - If the main goroutine reaches `wg.Wait()` before the spawned goroutines begin executing, the counter remains 0 and `Wait()` returns immediately, causing the program to terminate prematurely. 2. **Passing `sync.WaitGroup` by value:** - `WaitGroup` contains internal counter state. Passing by value creates a copy, leaving the original counter untouched and causing `wg.Wait()` to deadlock. Always pass a pointer (`*sync.WaitGroup`). --- ## 2. `sync.Mutex` & `sync.RWMutex` Mutual exclusion locks designed to control concurrent access to shared resources and prevent data races. ### `sync.Mutex` (Mutual Exclusion) - `.Lock()`: Acquires the lock. If another goroutine holds the lock, the caller blocks until it is available. - `.Unlock()`: Releases the lock. Always pair with `defer mu.Unlock()` to ensure locks are freed even during panics. ### `sync.RWMutex` (Reader/Writer Lock) Reduces the cross-section of critical sections by separating read and write access. - `.RLock()` / `.RUnlock()`: Read-only lock. An arbitrary number of readers can hold read locks concurrently as long as no writer holds the lock. - `.Lock()` / `.Unlock()`: Exclusive write lock. Only a single writer can hold this lock. ### Warning: RWMutex Self-Deadlock & Double-Checked Locking Go's `sync.RWMutex` **does not support lock promotion** (upgrading an active read lock to a write lock). Requesting a write lock while still holding a read lock results in an immediate self-deadlock. ```go // Idiomatic cache pattern with Double-Checked Locking func (c *Cache) GetOrSet(key, defaultValue string) string { // 1. Fast path: check with read lock c.mu.RLock() val, exists := c.data[key] c.mu.RUnlock() // Release immediately (do not defer) if exists { return val } // 2. Slow path: acquire write lock c.mu.Lock() defer c.mu.Unlock() // 3. Double-Check: another goroutine might have populated it between RUnlock and Lock if val, exists := c.data[key]; exists { return val } c.data[key] = defaultValue return defaultValue } ``` --- ## 3. `sync.Cond` (Condition Variables) A **rendezvous point** for goroutines waiting for or announcing the occurrence of an event. ### Why use `sync.Cond`? - **Busy Waiting:** Infinite loops consume 100% of a CPU core. - **Sleep Polling:** `time.Sleep` introduces artificial latency and wastes cycles. - **`sync.Cond`:** Suspends the goroutine in the runtime wait queue (**0% CPU utilization**) and wakes it up instantaneously when an event is signaled. ### Core Methods - `c.Wait()`: **[Hidden Side-Effect]** Automatically calls `c.L.Unlock()` to release the lock and suspends the goroutine. Upon waking up from a signal, it re-acquires `c.L.Lock()` before returning. - `c.Signal()`: Wakes up the single longest-waiting goroutine (1:1). - `c.Broadcast()`: Wakes up **all** waiting goroutines simultaneously (1:N). ### Golden Rule: Always Loop with `for`, Never `if` Upon waking up, another goroutine may have already acquired the lock and consumed the resource, or a spurious wakeup may have occurred. Always wrap `c.Wait()` inside a `for !condition` loop: ```go c.L.Lock() for !condition { c.Wait() } // Condition safely validated while holding the lock c.L.Unlock() ``` ### Standard Pattern (Producer-Consumer) ```go var ( mu sync.Mutex cond = sync.NewCond(&mu) queue []string ) // Consumer go func() { cond.L.Lock() for len(queue) == 0 { cond.Wait() // Suspended with 0% CPU until data arrives } item := queue[0] queue = queue[1:] fmt.Println("Processed:", item) cond.L.Unlock() }() // Producer cond.L.Lock() queue = append(queue, "task-1") cond.Signal() // Awaken 1 waiting worker (use cond.Broadcast() for all) cond.L.Unlock() ``` #### Lock Acquisition Order and Condition Re-checking In concurrent execution, it is indeterminate whether the Consumer or Producer acquires the lock first. The `for len(queue) == 0` loop ensures correctness regardless of arrival order: - **If Consumer arrives first:** The queue is empty, so it enters `cond.Wait()`, releasing the lock and sleeping. When the Producer acquires the lock, appends data, calls `Signal()`, and unlocks, the Consumer re-acquires the lock, wakes up, and consumes the item. - **If Producer arrives first:** It appends data and calls `cond.Signal()` (ignored since no goroutine is waiting yet). When the Consumer subsequently acquires the lock, `len(queue) == 0` evaluates to false, so it **bypasses `cond.Wait()` entirely and consumes the item immediately**. --- ## 4. `sync.Once` Guarantees that a specific initialization function is executed **exactly once** throughout the program's lifecycle, even across thousands of concurrent goroutines. - `.Do(f func())`: `f` must take no arguments and return no values. ### Idiomatic Pattern: Safe Channel Closer Closing an already closed channel causes `panic: close of closed channel`. Using `sync.Once` ensures safe closing even with multiple concurrent exit paths: ```go type SafeChannel struct { done chan struct{} once sync.Once } func (sc *SafeChannel) Close() { sc.once.Do(func() { close(sc.done) // Safely closed exactly once }) } ``` #### Equivalent Pattern Without `sync.Once` (`Mutex` + `select`) In older or low-level codebases (such as Kubernetes's `StreamWatcher.Stop()`), you will often see an equivalent pattern built with `sync.Mutex` and a non-blocking `select`. - **How it works:** For a pure signal channel (`chan struct{}`) that is never sent to and only closed, receiving (`<-ch`) becomes immediately ready the moment the channel is closed. Under a mutex lock, a `select` with a `default` branch checks whether the channel is already closed before calling `close()`. (Note: for channels that carry actual data, use an explicit `closed bool` flag under the mutex instead so you don't accidentally consume a value.) ```go type SafeChannel struct { done chan struct{} mu sync.Mutex } func (sc *SafeChannel) Close() { sc.mu.Lock() defer sc.mu.Unlock() // A closed channel is immediately readable; check before closing select { case <-sc.done: // Already closed; do nothing default: close(sc.done) // Close only if still open } } ``` ### Caveats - `sync.Once` tracks invocations on the `Once` instance itself, not the specific function passed to `Do`. Use distinct `sync.Once` variables for separate initialization tasks. ### Go 1.21+ Generic Helpers: `sync.OnceValue` vs `sync.OnceValues` While `sync.Once` is a struct requiring explicit calls to `.Do(func())`, Go 1.21+ introduced higher-order functions that **return callable (executable) functions directly**. #### 1. `sync.OnceValue[T]` (Single Value) - Signature: `func OnceValue[T any](f func() T) func() T` - Used for pure, infallible computations or settings where no error can occur. ```go var getHost = sync.OnceValue(func() string { return os.Getenv("HOST") }) func main() { host := getHost() // Directly callable function } ``` #### 2. `sync.OnceValues[T]` (Value and Error) - Signature: `func OnceValues[T any](f func() (T, error)) func() (T, error)` - Used for operations that may fail (DB connection, file I/O) following standard Go `(T, error)` conventions. ```go var getDB = sync.OnceValues(func() (*sql.DB, error) { return sql.Open("postgres", "connection_string") }) func main() { db, err := getDB() // Directly callable returning (*sql.DB, error) if err != nil { log.Fatal(err) } } ``` --- ## 5. `sync.Pool` A concurrent object pool designed to reuse temporary objects and **relieve Garbage Collector (GC) allocation pressure and stop-the-world pauses**. ### Core Architecture: Dynamic Pool, Not a Singleton - `sync.Pool` is **not** a singleton holding only a single object. - It is a **dynamic pool that scales up and down proportionally with the concurrent workload**. - If 100 goroutines call `Get()` concurrently, the pool scales to 100 objects, and when returned with `Put()`, all 100 objects remain available for subsequent reuse. ### Why is it in the `sync` Package? (Concurrency Optimization) Unlike a custom slice protected by a mutex, `sync.Pool` is deeply integrated with Go's GMP scheduler: - **Per-P Lock-Free Private Cache:** Each logical processor (`P`) has its own lock-free private cache, eliminating lock contention even under massive concurrency. - **Work-Stealing:** If a processor's local cache is empty, it steals idle objects from other processors. ### Methods and the Truth About `Reset()` - **`sync.Pool` provides only two methods:** - `.Get() any`: Retrieves an object or invokes `New()` if empty. - `.Put(x any)`: Returns an object to the pool. - **`Reset()` is NOT a `sync.Pool` method:** - `Reset()` belongs to the underlying concrete object (such as `bytes.Buffer`). - Because `sync.Pool` stores `any`, it has no knowledge of the object's internal structure and cannot clear it automatically. - **Callers must explicitly invoke `Reset()`** to prevent dirty reads or data contamination from prior operations. ### Basic Usage ```go var bufPool = sync.Pool{ New: func() any { return new(bytes.Buffer) // Factory called when pool is empty }, } func Render() string { // 1. Borrow and Type Assert buf := bufPool.Get().(*bytes.Buffer) defer func() { buf.Reset() // Essential: object method to reset state bufPool.Put(buf) // 2. Return }() buf.WriteString("Hello, Pool!") return buf.String() } ``` ### Practical Rules 1. **Not a Permanent Cache:** The Go runtime may sweep and reclaim objects in `sync.Pool` during any GC cycle. Never use it as a persistent store (e.g., Redis). 2. **Always `Reset()`:** Reused objects retain stale data from prior operations. Always clean buffers before or after use. 3. **Use Homogeneous Objects:** Store uniform items (e.g., standard byte buffers) rather than randomly-sized slices to maximize reuse efficiency.