When a group is not indivisible
An atomicity violation occurs when a sequence of operations that should execute as one indivisible unit is interrupted by another thread. Each step may be individually correct, but their interleaving produces an inconsistent result.
The canonical example
The read modify write on a counter looks like one line but is three steps:
- Read the current value.
- Add one.
- Write the result back.
If two threads read the same starting value, both add one, and both write, one increment is lost. The grouping that was supposed to be atomic was split.
Restoring atomicity
- Use an atomic instruction such as fetch and add, which performs the whole read modify write indivisibly.
- Protect the group with a lock so no other thread interleaves between the steps.
- Use a transaction that commits all or nothing.
Key idea
An atomicity violation splits a group that must be indivisible. Use atomic instructions, locks, or transactions to keep the steps together.