Atomics and Operators
suggest changeAtomic objects can be accessed concurrently without creating a data race, provided every conflicting access to the object is atomic.
#include <stdatomic.h>
static _Atomic unsigned active = 0;
int worker(void *context)
{
(void)context;
++active; /* Atomic read-modify-write. */
/* Do work. */
--active; /* Atomic read-modify-write. */
return 0;
}
Operators such as ++, --, +=, and -= perform atomic read-modify-write operations when their operand is atomic. By contrast, this expression is not a single atomic increment:
active = active + 1;
The load and store are individually atomic, but another thread can update active between them, causing a lost update. Use active++, active += 1, or atomic_fetch_add when the entire update must be indivisible.
Atomic operations can cost more than ordinary accesses because they constrain optimization and may require synchronization between processor cores. The cost depends on the type, target, contention, and memory order; it is not necessarily orders of magnitude greater. The operators above use sequentially consistent ordering. The functions in <stdatomic.h> allow an explicit, weaker memory order when the algorithm permits one.