C Programming • C17 baseline, standards-specific features labeled
Threads, Atomics, and the C Memory Model
Coordinate shared state using synchronization rather than assuming ordinary reads and writes are safe.
C11 introduced atomics and a standardized thread API, though implementations may not provide every optional facility. Conflicting unsynchronized accesses to the same non-atomic object create a data race and undefined behavior. volatile does not make a data race safe.
Example
#include <stdatomic.h>
static atomic_uint completed = 0;
void mark_completed(void) {
atomic_fetch_add_explicit(&completed, 1u, memory_order_relaxed);
}
unsigned completed_count(void) {
return atomic_load_explicit(&completed, memory_order_relaxed);
}
What to expect
Atomic increments and loads avoid a data race for this independent counter; relaxed ordering does not publish other data.
Key idea: Choose memory ordering based on the synchronization relationship you need, and prefer a mutex when it makes the invariant clearer.