Atomics
An atomic object is one the compiler and CPU will not tear or race on. C11 <stdatomic.h> gives _Atomic types and operations with an explicit memory order.
Detailed Explanation
A data race is two threads accessing one object, at least one writing, without synchronization. The program is then undefined. _Atomic int counter; plus atomic_fetch_add(&counter, 1) is not a data race. The increment happens as one operation.
atomic_load, atomic_store, atomic_exchange, atomic_compare_exchange_strong, and the fetch_* family are the toolkit. The default order is memory_order_seq_cst, the strongest: there is a single global order of seq-cst operations that all threads agree on. Weaker orders (relaxed, acquire, release, acq_rel) exist to cheapen the barriers on some CPUs. They are easy to get wrong. Start with seq-cst. Weaken when a profile says the barrier is the cost and a reviewer can prove the order.
Atomics are for words: flags, counters, pointers, generation numbers. They are not a substitute for a mutex around a multi-field invariant. Making every field _Atomic does not make "length matches buffer" atomic. Two loads can still see a torn pair.
atomic_flag is the one type guaranteed to be lock-free. Larger _Atomic structs may be implemented with a secret lock; atomic_is_lock_free tells you. A "lock-free" algorithm that uses a secret lock under a 16-byte atomic can deadlock if you are not careful in a signal handler.
C11 atomics need a compiler that implements them (any current GCC/Clang) and sometimes -latomic for 64-bit atomics on 32-bit targets. They are the replacement for ad-hoc __sync_* builtins and for volatile as a concurrency tool.
Code Examples
#include <stdatomic.h>
#include <pthread.h>
#include <stdio.h>
static _Atomic int counter;
static void *add(void *arg)
{
int n = *(int *)arg;
for (int i = 0; i < n; i++) {
atomic_fetch_add(&counter, 1);
}
return NULL;
}
int main(void)
{
int n = 100000;
pthread_t a, b;
pthread_create(&a, NULL, add, &n);
pthread_create(&b, NULL, add, &n);
pthread_join(a, NULL);
pthread_join(b, NULL);
printf("%d\n", atomic_load(&counter)); /* prints: 200000 */
return 0;
}#include <stdatomic.h>
#include <stdio.h>
int main(void)
{
_Atomic int flag = 0;
atomic_store(&flag, 1);
if (atomic_load(&flag)) {
printf("set\n"); /* prints: set */
}
return 0;
}Common Gotchas
A plain `int` incremented by two threads is a data race even if you have seen it "work"
the optimizer and the CPU are both allowed to lose updates.
`_Atomic` on each field does not make a multi-field invariant atomic
use a mutex for the group.
`volatile` is not atomic
it suppresses some optimizations and does not define a data race away.
Weak memory orders can reorder surrounding plain accesses
if you cannot name the acquire/release pair, stay on `seq_cst`.