Visibility and store buffers
advanced · commonly asked
Two threads write, then read each other. Under sequential consistency both reading zero is impossible; on real hardware it happens — and no interleaving explains it.
Enumerating the interleavings…
What this shows
A write is not visible when it happens, it is visible when it is published. This is where the interleaving model runs out and a memory model is required.
Why it is asked
What `volatile` actually guarantees, and why it is about publication rather than atomicity. Most candidates have this exactly backwards.
In an interview
What `volatile` actually guarantees, and why it is about publication rather than atomicity. Most candidates have this exactly backwards.
- memory model
- volatile
- store buffer
- happens-before
Run these next
- Memory barriersA barrier does not make anything atomic. It forces publication, which is a different guarantee and the one the reordering was violating.
- 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.
- Atomic operationsAtomicity 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.