Atomic operations
foundational · commonly asked
The same counter with an atomic increment. Watch the outcome space collapse from two states to one — not fewer bad orderings, none.
Enumerating the interleavings…
What this shows
Atomicity is not speed and not a lock. It is indivisibility: no interleaving can slot between the read and the write, so the orderings that lost updates cease to exist.
Why it is asked
The follow-up to every lost-update answer. Knowing when an atomic suffices and when you still need a lock is the actual dividing line.
In an interview
The follow-up to every lost-update answer. Knowing when an atomic suffices and when you still need a lock is the actual dividing line.
- atomics
- compare-and-swap
- lock-free
Run these next
- The lost update`count++` is three operations, not one. Only two of its twenty interleavings produce 2; the failure is the common case, and an atomic increment removes the orderings rather than making them rarer.
- MutexesA lock removes orderings from the space. The critical section must span the whole read-modify-write — guarding only the write leaves the window exactly where it was.