Learn C
#include "advanced/atomics.h"

Atomics with stdatomic.h (C11) in C

#concept

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.

#how it works
1

Atomic variables

_Atomic int n = 0; — every load/store/add on n happens indivisibly, visible coherently to all threads.

2

Fetch-and-operate

atomic_fetch_add(&n, 1) returns the old value while adding — lock-free counters in one call.

3

Default to seq_cst

Plain atomic operations order sequentially-consistently — the intuitive model. Weaker orders trade reasoning for speed.

4

Singles only

Atomics guard one variable each — coordinated multi-variable updates still belong under mutexes.

#example
#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;
}
Output
2
1hits starts 0 as an atomic int — every access through atomic functions is indivisible.
2Two fetch-adds (each returning the pre-value, ignored here) accumulate safely even under threads.
3atomic_load reads 2 — coherent, race-free, mutex-free.
#use cases
Lock-free counters, flags, and statistics in threaded code
Shutdown and ready flags shared between threads
Keeping seq_cst until measurement justifies weaker orders
Mutexes for every multi-variable invariant atomics can't cover

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.