The Atomic Counter
A counter shared by many threads looks innocent but hides a trap. The statement that increments it is really three steps: read the current value, add one, write it back. If two threads read the same value before either writes, both produce the same result and one increment vanishes. This is a lost update, the simplest data race.
An atomic counter fixes this by making the read add write happen as one indivisible step. The hardware exposes an instruction, often called fetch and add, that performs the whole operation while no other core can observe a half finished value.
- Indivisible No other thread can slip between the read and the write.
- Lock free A single atomic instruction needs no mutex, so there is no risk of a blocked holder stalling everyone.
- Cheap for one variable but it does not compose, two atomic counters updated together are still not atomic as a pair.
Atomics are the building block under reference counts, statistics, and unique id generators. They are fast precisely because they protect exactly one word and nothing more.
Key idea
An atomic counter folds read add write into one indivisible hardware instruction so concurrent increments never lose updates.