Back to Home

Memory Ordering & Visibility

See why CPU caches can cause threads to see stale values

🧠 Why CPUs Lie to You

Modern CPUs reorder instructions and use local caches for performance. This means one thread's writes may appear in a different order to another thread! Without proper synchronization, you can read "stale" data that hasn't been updated yet.

⚠️ The Problem

  • • CPU may reorder writes for optimization
  • • Each core has its own L1/L2 cache
  • • Writes sit in store buffers before memory
  • • Result: Thread A's changes invisible to Thread B

✓ The Solution

  • Release: Flush writes before this point
  • Acquire: Sync cache before reading
  • SeqCst: Full ordering (safest, slowest)
  • • Atomics with proper memory ordering

🎬 What to Watch

In the broken scenario, Core 2 sees ready=true but stale data=0 due to reordering. In the fixed scenario, memory barriers ensure proper ordering.

The Classic Pattern

// Thread 1 (Producer)              // Thread 2 (Consumer)
data = 42;                          while (!ready) { }
ready = true;                       console.log(data); // ???

// Without memory barriers, Thread 2 might see:
// ready=true but data=0 (stale!)

CPU & Memory Architecture

Core 1 (Writer)
Local Cache:
data = 0
Cache
Coherence
M
Main Memory
data:0
ready:false
Cache
Coherence
Core 2 (Reader)
Local Cache:
data = 0
Progress: Step 0/5

Event Log

Click a scenario to start...

Memory Barriers

Release:

Flush all writes before this point

Acquire:

Sync cache before reading

SeqCst:

Both + total ordering

Why CPUs Reorder

  • • Store buffers delay writes
  • • Out-of-order execution
  • • Cache coherence latency
  • • Compiler optimizations