Writes that vanish
A memory visibility bug is when one thread updates a variable and another thread keeps reading a stale value, sometimes forever. The update happened, but nothing forced it to become visible across cores.
Why this is allowed
Modern hardware and compilers optimize aggressively:
- Each core has caches, and a write may sit there before reaching shared memory.
- Compilers may hoist a repeated read out of a loop into a register, so the loop never re reads memory.
- Instructions may be reordered as long as single thread behavior is preserved.
A common symptom is a spin loop on a plain stop flag that another thread sets, yet the spinner never exits.
Establishing visibility
- Use volatile or atomic reads and writes, which forbid the read from being cached in a register and add ordering.
- Use locks, which create happens before edges: everything before an unlock is visible after the matching lock.
- Use explicit memory barriers at the lowest level.
Key idea
A write is not automatically visible to other threads. Use volatile, atomics, or locks to create the happens before ordering that makes updates appear.