Increment a shared counter with atomic_fetch_add_explicit
Increment a shared counter from several threads with C11 atomic_fetch_add_explicit and memory_order_relaxed, which also returns the old value.
A plain counter++ shared between threads is a data race: two threads can read the same value and both write back one more. C11's atomic_fetch_add_explicit performs the read-modify-write as one indivisible step and returns the value from before the addition. Pass memory_order_relaxed when the counter orders nothing else. This is GCC 13 with -std=c11 -pthread, in <stdatomic.h>.
#include <pthread.h>
#include <stdatomic.h>
#include <stdio.h>
static atomic_int counter;
static void *worker(void *arg)
{
(void)arg;
for (int i = 0; i < 100000; i++)
atomic_fetch_add_explicit(&counter, 1, memory_order_relaxed);
return NULL;
}
int main(void)
{
pthread_t t[4];
for (int i = 0; i < 4; i++) pthread_create(&t[i], NULL, worker, NULL);
for (int i = 0; i < 4; i++) pthread_join(t[i], NULL);
printf("counter=%d\n", atomic_load(&counter));
return 0;
}counter=400000Nothing is lost, and the joins give the final read all the ordering it needs. The explicit form exists to choose the ordering; the plain atomic_fetch_add means memory_order_seq_cst, the strongest and, on some CPUs, a costlier instruction sequence. Relaxed is right only for pure counters; if another variable's value depends on the count, you need acquire and release. See atomic_fetch_add.