Atomics with stdatomic.h (C11) in C
C11 atomics (<stdatomic.h>) make single variables safely shareable between threads: _Atomic int counter; with atomic_fetch_add(&counter, 1) increments indivisibly — no mutex, no race, no torn reads. Memory orders (memory_order_relaxed through seq_cst, the default) tune how much cross-thread ordering each operation guarantees.
Atomics cover single variables, not transactions — multi-field invariants still need mutexes. sticking to seq_cst defaults is correct until profiling proves otherwise; relaxed ordering is an expert tool for measured hot paths, not a default.
Atomic variables
_Atomic int n = 0; — every load/store/add on n happens indivisibly, visible coherently to all threads.
Fetch-and-operate
atomic_fetch_add(&n, 1) returns the old value while adding — lock-free counters in one call.
Default to seq_cst
Plain atomic operations order sequentially-consistently — the intuitive model. Weaker orders trade reasoning for speed.
Singles only
Atomics guard one variable each — coordinated multi-variable updates still belong under mutexes.
#include <stdio.h>#include <stdatomic.h> int main(void) { _Atomic int hits = 0; atomic_fetch_add(&hits, 1); atomic_fetch_add(&hits, 1); printf("%d\n", atomic_load(&hits)); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.