<stdatomic.h> provides _Atomic type and lock-free atomic operations for thread synchronization (C11). Atomic operations complete without interruption and support compare-and-swap for building lock-free data structures.
Memory order control (relaxed, acquire, release, seq_cst) allows trading off ordering guarantees for performance.
This example uses atomic operations to safely increment a counter from multiple threads.
// compile: gcc -std=c11 -pthread -o atomicexample atomicexample.c // run: ./atomicexample // description: thread-safe counter using atomic operations #include <stdatomic.h> #include <pthread.h> #include <stdio.h> atomic_int counter = 0; void* worker(void* arg) { for (int i = 0; i < 100000; i++) { atomic_fetch_add_explicit(&counter, 1, memory_order_relaxed); } return NULL; } int main() { pthread_t t1, t2; pthread_create(&t1, NULL, worker, NULL); pthread_create(&t2, NULL, worker, NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); printf("counter = %d (expected 200000)\n", atomic_load(&counter)); return 0; }
Atomic types:
_Atomic(T): atomic version of type Tatomic_int, atomic_long, atomic_uint, etc.: common atomic type aliasesATOMIC_VAR_INIT(value): initialize atomic variableLoad/store:
atomic_load(&a): load with sequential consistencyatomic_load_explicit(&a, order): load with specific orderatomic_store(&a, v): store with sequential consistencyatomic_store_explicit(&a, v, order): store with specific orderArithmetic operations:
atomic_fetch_add(&a, v): increment and return old valueatomic_fetch_sub(&a, v): decrement and return old valueatomic_fetch_and(&a, v): bitwise AND and return old valueatomic_fetch_or(&a, v): bitwise OR and return old valueatomic_fetch_xor(&a, v): bitwise XOR and return old valueCompare and swap:
atomic_compare_exchange_strong(&a, &exp, new): CAS operationatomic_compare_exchange_weak(&a, &exp, new): weak CAS (may fail spuriously)
Memory orders (for _explicit functions):
memory_order_relaxed: no synchronizationmemory_order_acquire: acquire semantics (for load)memory_order_release: release semantics (for store)memory_order_acq_rel: both acquire and releasememory_order_seq_cst: sequential consistency (default)