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/ # Mutex vs Atomic The two foundational primitives for eliminating Data Races in shared-memory concurrency are **Mutexes** and **Atomic operations**. They differ fundamentally in the scope of state they can protect and how they handle contention. --- ## 1. Core Comparison | Dimension | **Mutex** | **Atomic** | | :--- | :--- | :--- | | **Protected Scope** | **Multiple variables, multi-statement blocks, entire composite data structures** | **A single scalar or pointer variable, a single operation** | | **Contention Behavior** | OS kernel or runtime scheduler **blocks** the contending thread and performs a Context Switch | Never sleeps; completes directly via **a single CPU hardware instruction** (eg. `LOCK XADD`, **Lock-free**) | | **Typical Cost** | Microseconds under contention (kernel transition and scheduling overhead) | Nanoseconds (hardware cache-coherency protocol overhead) | | **Typical Use Cases** | Linked-list/map mutations, multi-field invariants | Single counters, state flags, reference counting | --- ## 2. Shared Rule: Every Access Path Must Synchronize A common misconception is that only Writers modifying a variable need Mutexes or Atomic operations while Readers can read the variable plainly without synchronization. - **One-sided synchronization is still a Data Race**: Even if every Writer uses a Mutex or an Atomic write, an unsynchronized plain read on the Reader side remains vulnerable to Torn Reads, stale per-core caches, and compiler/CPU instruction reordering. - **Every concurrent read and write path touching the shared variable must use the same synchronization discipline** — either all guarded by the same Mutex, or all accessed through Atomic operations. ### Language Design Comparison for Preventing Accidental Plain Access - **Function-based APIs** (eg. legacy Go `sync/atomic.AddUint64(&x, 1)`): Operate on an ordinary `uint64` variable, so accidentally writing a plain read `v := x` elsewhere compiles cleanly while introducing a silent Data Race. - **Type-enforced APIs** (eg. C11 `_Atomic`, C++ `std::atomic`, Go 1.19+ `atomic.Uint64`): Encode atomicity in the variable's type itself, preventing accidental non-atomic accesses at compile time. See [C `stdatomic`]({{< relref "/programming/c/stdatomic.md" >}}). --- ## 3. Selection Criteria and Real-World Contrast ### 1. When a Mutex Is Required: Multi-Variable Invariants Whenever two or more fields must change together to preserve a structural invariant, single-variable Atomics cannot group them into one indivisible transition. Real-world example — appending a node to a doubly linked list ([HAMi-core `allocator.c#L151-L163`](https://github.com/Project-HAMi/HAMi-core/blob/8417257eecce03ae34d1711bf47002d70b5bfc12/src/allocator/allocator.c#L151-L163)): ```c int add_chunk_only(CUdeviceptr address, size_t size, CUdevice dev) { allocated_list_entry *e; // LIST_ADD updates head, tail, prev, next, and length together; // single-variable Atomics cannot guard this multi-field invariant, so a Mutex is required pthread_mutex_lock(&mutex); if (new_allocated_list_entry(&e, 0, size, dev) != 0) { pthread_mutex_unlock(&mutex); return -1; } e->entry->address = address; LIST_ADD(device_overallocated, e); pthread_mutex_unlock(&mutex); return 0; } ``` ### 2. When Atomics Fit: Independent Single-Variable Operations When incrementing a standalone counter or reading/updating a single flag with no cross-field invariant, Atomics avoid Lock acquisition and Context Switch overhead entirely. Real-world example — accumulating a single memory usage counter ([HAMi-core `multiprocess_memory_limit.c#L518`](https://github.com/Project-HAMi/HAMi-core/blob/8417257eecce03ae34d1711bf47002d70b5bfc12/src/multiprocess/multiprocess_memory_limit.c#L518)): ```c // Atomic addition and atomic load on a single 64-bit counter atomic_fetch_add_explicit(&slot->used[dev].total, usage, memory_order_release); uint64_t used = atomic_load_explicit(&slot->used[dev].total, memory_order_acquire); ```