Skip to content
Tutorials Center
My learning

Topics

C Reference ยท ctype.h, math.h and others

C stdatomic.h: atomic types and operations

Reference for stdatomic.h: _Atomic types, atomic_load, atomic_store, atomic_fetch_add, compare-exchange loops, atomic_flag and the memory_order options explained.

An atomic object can be read and written by several threads at the same time without a data race. Operations on it are indivisible: another thread sees either the old value or the new one, never half of each. <stdatomic.h> provides atomic versions of the integer types (atomic_int, atomic_long, atomic_bool, atomic_size_t, ...), the generic qualifier _Atomic, and functions such as atomic_load, atomic_store, atomic_fetch_add, atomic_exchange and atomic_compare_exchange_strong.

Atomics are the lightweight alternative to a mutex when the shared state is a single counter, flag or pointer. They also define how memory writes become visible to other threads, which is what the memory_order arguments control. If you are not sure, use the functions without _explicit: they use the strongest and safest ordering.

C
#include <stdatomic.h>

atomic_int hits = 0;
atomic_fetch_add(&hits, 1);          /* indivisible increment */
int now = atomic_load(&hits);

Try it

C The basic operations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C Threads: a counter, a maximum and publishing data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Syntax

C
#include <stdatomic.h>

_Atomic(T) x;   atomic_int x;   atomic_bool b;   atomic_flag f = ATOMIC_FLAG_INIT;

T atomic_load(const volatile A *obj);
void atomic_store(volatile A *obj, C desired);
T atomic_exchange(volatile A *obj, C desired);
bool atomic_compare_exchange_strong(volatile A *obj, C *expected, C desired);
bool atomic_compare_exchange_weak(volatile A *obj, C *expected, C desired);
T atomic_fetch_add(volatile A *obj, M arg);  /* also _sub, _or, _xor, _and */
bool atomic_is_lock_free(const volatile A *obj);
bool atomic_flag_test_and_set(volatile atomic_flag *f);   void atomic_flag_clear(volatile atomic_flag *f);
void atomic_thread_fence(memory_order order);   void atomic_signal_fence(memory_order order);
/* each operation also exists with an _explicit suffix and a memory_order argument */
Name Description
atomic_load, atomic_store Read or write the value indivisibly.
atomic_exchange Store a new value and return the old one in one step.
atomic_fetch_op Apply +, -, |, ^ or & and return the previous value.
atomic_compare_exchange_* If *obj == *expected, store desired and return true; otherwise copy the current value into *expected and return false. The weak form may fail spuriously and is meant for loops.
memory_order_relaxed Atomicity only, no ordering of other memory accesses. Fine for counters.
memory_order_acquire / release A release store makes earlier writes visible to a thread whose acquire load sees that store.
memory_order_acq_rel, memory_order_seq_cst Combined ordering; seq_cst (the default) also gives a single global order.
memory_order_consume Dependency-ordered reads; in practice treated as acquire. Avoid.

Returns: loads and fetch operations return the value; exchange returns the previous value; compare-exchange returns whether it succeeded; atomic_flag_test_and_set returns the previous state.

Errors / undefined behavior: accessing an atomic object through a non-atomic lvalue while other threads use it is a data race. Using memory_order_release for a load, or acquire for a store, is undefined. Atomics must be initialized (ATOMIC_VAR_INIT is deprecated; plain initialization works), and an atomic_flag should start with ATOMIC_FLAG_INIT or be static.

Usage notes

  • Default to sequential consistency. Plain functions (atomic_load, atomic_store) and compound operators (x++, x += n on _Atomic objects) use memory_order_seq_cst. Switch to _explicit only after measuring.
  • Release/acquire pairs publish data. Everything written before a release store is visible after an acquire load that reads the stored value, as in the second example. Relaxed operations give no such guarantee.
  • Atomic is not the same as safe. Two separate atomic operations are not atomic together: if (atomic_load(&x) == 0) atomic_store(&x, 1) has a race. Use compare_exchange, or a mutex for several variables that must change together.
  • volatile is not atomic. It only prevents some optimizations. See volatile.
  • Compare-exchange loops are the building block of lock-free structures: read the current value, compute a new one, try to swap, retry on failure. weak is usually cheaper in a loop; strong is simpler outside one.
  • Lock-free or not. Small atomic types are usually lock-free on mainstream CPUs (check ATOMIC_INT_LOCK_FREE, atomic_is_lock_free). Large _Atomic structs may fall back on a hidden lock (and need -latomic with some compilers).
  • Pointers and sizes. atomic_intptr_t, atomic_size_t and _Atomic(T *) exist. The ABA problem and memory reclamation make lock-free pointer structures hard; prefer mutexes unless you must.
  • atomic_flag busy-waits. A spin lock built on it burns CPU while waiting and, on a single core, can waste the whole time slice; yield or use a mutex.
  • Cost. An uncontended atomic increment costs a few nanoseconds; heavily contended ones bounce a cache line between cores and can be slower than a mutex.
  • Standard version: C11 (optional: __STDC_NO_ATOMICS__ marks its absence). ATOMIC_VAR_INIT is deprecated since C17; plain initialization is enough.