Site Tools


h-stdatomic

<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;
}

Common functions and types

Atomic types:

  • _Atomic(T): atomic version of type T
  • atomic_int, atomic_long, atomic_uint, etc.: common atomic type aliases
  • ATOMIC_VAR_INIT(value): initialize atomic variable

Load/store:

  • atomic_load(&a): load with sequential consistency
  • atomic_load_explicit(&a, order): load with specific order
  • atomic_store(&a, v): store with sequential consistency
  • atomic_store_explicit(&a, v, order): store with specific order

Arithmetic operations:

  • atomic_fetch_add(&a, v): increment and return old value
  • atomic_fetch_sub(&a, v): decrement and return old value
  • atomic_fetch_and(&a, v): bitwise AND and return old value
  • atomic_fetch_or(&a, v): bitwise OR and return old value
  • atomic_fetch_xor(&a, v): bitwise XOR and return old value

Compare and swap:

  • atomic_compare_exchange_strong(&a, &exp, new): CAS operation
  • atomic_compare_exchange_weak(&a, &exp, new): weak CAS (may fail spuriously)

Memory orders (for _explicit functions):

  • memory_order_relaxed: no synchronization
  • memory_order_acquire: acquire semantics (for load)
  • memory_order_release: release semantics (for store)
  • memory_order_acq_rel: both acquire and release
  • memory_order_seq_cst: sequential consistency (default)
h-stdatomic.md · Last modified: by 127.0.0.1