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/ # `stdatomic` The C11 standard (``) provides hardware-level atomic memory operations and a formal memory model directly in the language without platform-specific inline assembly. --- ## 1. Why Atomic Operations Are Needed Concurrent reads and writes to ordinary variables across multiple threads or `mmap` shared-memory processes introduce two fundamental hazards: - **Lost Update**: An increment such as `total += 100` compiles into three separate machine steps: 1) memory `Load`, 2) register `Add`, and 3) memory `Store`. If two threads read `1000` at the same time, both store `1100`, losing one increment. - **Torn Read**: If one thread reads a 64-bit variable while another thread is halfway through updating it, the reader can observe a corrupted value combining the old upper 32 bits with the new lower 32 bits. Atomic operations use CPU hardware instructions (eg. x86 `LOCK XADD`, ARM `LDADD`) to execute the access as a **single indivisible step**, preventing both Lost Updates and Torn Reads. --- ## 2. The `_Atomic` Keyword `_Atomic` is a C11 type qualifier keyword placed before a type, just like `const` or `volatile`. ```c #include #include _Atomic uint64_t total = 0; _Atomic int32_t pid = 0; ``` - **Naming Rationale**: To avoid breaking legacy pre-C11 codebases that already used `atomic` as an identifier for variables or functions, C11 introduced new keywords with a leading underscore and capital letter (`_Atomic`, `_Bool`, `_Thread_local`). - **Default Operator Atomicity**: Accessing an `_Atomic`-qualified variable through ordinary operators such as `total += 10` or `x = total` is automatically compiled as a `memory_order_seq_cst` atomic operation. Use the `*_explicit` functions below when choosing a lighter ordering (`relaxed`, `acquire`, `release`). --- ## 3. Core Functions and Signatures (``) Because C lacks function overloading, `` defines its operations as type-generic macros that adapt to any `_Atomic` pointer type (eg. GCC's `stdatomic.h` uses `__auto_type` and `__atomic_*` builtins). ```c #include // 1. Atomic load and store C atomic_load_explicit(const volatile A *obj, memory_order order); void atomic_store_explicit(volatile A *obj, C desired, memory_order order); // 2. Atomic read-modify-write arithmetic (returns the previous value before modification) C atomic_fetch_add_explicit(volatile A *obj, M arg, memory_order order); C atomic_fetch_sub_explicit(volatile A *obj, M arg, memory_order order); // 3. Compare-And-Swap (replaces *obj with desired if *obj == *expected; otherwise writes current *obj into *expected) _Bool atomic_compare_exchange_weak_explicit(volatile A *obj, C *expected, C desired, memory_order succ, memory_order fail); // 4. Standalone memory barrier without accessing a variable void atomic_thread_fence(memory_order order); ``` - **Signature Type Placeholders (`A`, `C`, `M`)**: Not actual C keywords written in source code, but documentation placeholders used by the ISO C11 specification and manual pages to describe type-generic macro relationships. - `A`: The `_Atomic`-qualified target type (eg. `_Atomic uint64_t`, `_Atomic(int *)`) - `C`: The corresponding non-atomic value type (eg. `uint64_t`, `int *`) - `M`: The modification delta type. For integer atomics `M` is identical to `C`, whereas for pointer atomics (`_Atomic(T *)`) two pointers cannot be added, so `M` becomes the signed pointer-offset integer type `ptrdiff_t`. - Shorthand forms without `_explicit` (eg. `atomic_load(obj)`) default to the most expensive `memory_order_seq_cst`; systems code typically uses `*_explicit` to specify the exact ordering needed. --- ## 4. `memory_order` and Preventing Reordering ### 1. Difference from Locks and Origin of `release` / `acquire` `memory_order` is not a mutual-exclusion Lock that blocks other threads. Instead, it constrains the **two entities that reorder instructions for performance — compiler optimizations and CPU Out-of-Order Execution — forcing them to preserve the memory visibility order written in code**. The names `release` (for writes) and `acquire` (for reads) come directly from Mutex **`unlock` (Lock Release) and `lock` (Lock Acquire)** semantics: - Just as **releasing** (`unlock`) a Mutex publishes all modifications made inside the critical section to other threads, a `memory_order_release` write guarantees that all prior memory writes become visible before the release write itself. - Just as **acquiring** (`lock`) a Mutex ensures subsequent reads see the latest published state, a `memory_order_acquire` read guarantees that subsequent memory reads execute only after the acquire read completes. ### 2. Primary `memory_order` Levels | Constant | Target Operation & Prohibited Reordering Direction | | :--- | :--- | | **`memory_order_relaxed`** | Guarantees atomicity of that single variable only; allows reordering with surrounding memory operations (used for simple counters) | | **`memory_order_release`** | Used on writes (`store`, `fetch_add`). **Prevents any memory read or write above this line from being reordered below it** | | **`memory_order_acquire`** | Used on reads (`load`). **Prevents any memory read or write below this line from being reordered above it** | | **`memory_order_seq_cst`** | Enforces Release + Acquire ordering plus a single global total order observed identically by all CPU cores | - **`atomic_thread_fence(order)`**: Places a compiler and CPU hardware Memory Barrier at that point in code without reading or writing an atomic variable. --- ## 5. Practical Pattern: Seqlock (1 Writer, N Readers) Allows Readers to read a consistent multi-field snapshot without acquiring a Lock while a Writer updates related fields together (eg. Linux kernel timekeeping, [HAMi-core `multiprocess_memory_limit.c`](https://github.com/Project-HAMi/HAMi-core/blob/8417257eecce03ae34d1711bf47002d70b5bfc12/src/multiprocess/multiprocess_memory_limit.c)). - **Precondition**: Writers must be serialized by a separate Mutex or Semaphore so **at most one Writer** updates the slot at a time (eg. [HAMi-core `allocator.c#L60-L69`](https://github.com/Project-HAMi/HAMi-core/blob/8417257eecce03ae34d1711bf47002d70b5bfc12/src/allocator/allocator.c#L60-L69)). Readers, by contrast, run concurrently without any Lock. - **Mechanism**: The `seqlock` counter starts at `0` (even). The Writer increments it by `+1` on entry (odd: `1, 3, 5...`) and by `+1` again on exit (even: `2, 4, 6...`). ### 1. Writer Pattern Real-world example: [HAMi-core `multiprocess_memory_limit.c#L514-L533`](https://github.com/Project-HAMi/HAMi-core/blob/8417257eecce03ae34d1711bf47002d70b5bfc12/src/multiprocess/multiprocess_memory_limit.c#L514-L533) ```c // Entered while holding the Writer Semaphore atomic_fetch_add_explicit(&slot->seqlock, 1, memory_order_release); // 0 -> 1 (odd: update in progress) atomic_fetch_add_explicit(&slot->used[dev].total, usage, memory_order_release); atomic_fetch_add_explicit(&slot->used[dev].module_size, usage, memory_order_release); // release guarantee: neither update above can sink below this line, so once // seqlock becomes even (2), both fields are guaranteed to be committed atomic_fetch_add_explicit(&slot->seqlock, 1, memory_order_release); // 1 -> 2 (even: update complete) ``` ### 2. Reader Pattern - **Failure Without Seqlock**: Starting from `(total = 100, module_size = 0)`, suppose a Writer adds `+50`. If a Reader reads the two variables right after `total` becomes `150` but before `module_size` becomes `50`, it observes `(total = 150, module_size = 0)` — **an inconsistent cross-field snapshot**. - **Seqlock Resolution**: If `seqlock` is odd or changes between the start and end of the read (`seq1 != seq2`), the Reader discards the torn snapshot and retries, guaranteeing it only ever observes `(100, 0)` or `(150, 50)`. Real-world example: [HAMi-core `multiprocess_memory_limit.c#L379-L422`](https://github.com/Project-HAMi/HAMi-core/blob/8417257eecce03ae34d1711bf47002d70b5bfc12/src/multiprocess/multiprocess_memory_limit.c#L379-L422) ```c uint64_t seq1, seq2, total, mod; do { seq1 = atomic_load_explicit(&slot->seqlock, memory_order_acquire); while (seq1 & 1) { // Odd means Writer is mid-update; spin until it turns even seq1 = atomic_load_explicit(&slot->seqlock, memory_order_acquire); } total = atomic_load_explicit(&slot->used[dev].total, memory_order_acquire); mod = atomic_load_explicit(&slot->used[dev].module_size, memory_order_acquire); atomic_thread_fence(memory_order_acquire); // Prevents the data reads above from sinking past seq2 seq2 = atomic_load_explicit(&slot->seqlock, memory_order_acquire); } while (seq1 != seq2); // Discard and retry if a Writer intervened (eg. 0 != 2) ``` {{% hint info %}} When reading only a **single atomic variable** (eg. `total` alone rather than matching `total` against `module_size`), cross-field inconsistency cannot occur, so a single `atomic_load_explicit(&slot->used[dev].total, memory_order_acquire)` suffices without a Seqlock loop. {{% /hint %}}