wiki:h-stdatomic
Table of Contents
<stdatomic.h>
<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.
Example
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; }
wiki/h-stdatomic.md · Last modified: by 127.0.0.1
