stdatomic#
The C11 standard (<stdatomic.h>) 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 += 100compiles into three separate machine steps: 1) memoryLoad, 2) registerAdd, and 3) memoryStore. If two threads read1000at the same time, both store1100, 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.
#include <stdint.h>
#include <stdatomic.h>
_Atomic uint64_t total = 0;
_Atomic int32_t pid = 0;- Naming Rationale: To avoid breaking legacy pre-C11 codebases that already used
atomicas 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 astotal += 10orx = totalis automatically compiled as amemory_order_seq_cstatomic operation. Use the*_explicitfunctions below when choosing a lighter ordering (relaxed,acquire,release).
3. Core Functions and Signatures (<stdatomic.h>)#
Because C lacks function overloading, <stdatomic.h> 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).
#include <stdatomic.h>
// 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 atomicsMis identical toC, whereas for pointer atomics (_Atomic(T *)) two pointers cannot be added, soMbecomes the signed pointer-offset integer typeptrdiff_t.
- Shorthand forms without
_explicit(eg.atomic_load(obj)) default to the most expensivememory_order_seq_cst; systems code typically uses*_explicitto 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, amemory_order_releasewrite 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, amemory_order_acquireread 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).
- 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). Readers, by contrast, run concurrently without any Lock. - Mechanism: The
seqlockcounter starts at0(even). The Writer increments it by+1on entry (odd:1, 3, 5...) and by+1again on exit (even:2, 4, 6...).
1. Writer Pattern#
Real-world example: HAMi-core multiprocess_memory_limit.c#L514-L533
// 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 aftertotalbecomes150but beforemodule_sizebecomes50, it observes(total = 150, module_size = 0)— an inconsistent cross-field snapshot. - Seqlock Resolution: If
seqlockis 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
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)
When reading only a single atomic variable (eg.
totalalone rather than matchingtotalagainstmodule_size), cross-field inconsistency cannot occur, so a singleatomic_load_explicit(&slot->used[dev].total, memory_order_acquire)suffices without a Seqlock loop.