← Lessons

quiz vs the machine

Gold1480

Concurrency

The Memory Visibility Bug

A write one thread made that another thread may never see.

5 min read · core · beat Gold to climb

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.

Check yourself

Answer to earn rating on the learn ladder.

1. Why might a thread never see another thread's write to a plain flag?

2. Which mechanism guarantees visibility of a shared flag?