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.
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.
// 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!)Click a scenario to start...
Flush all writes before this point
Sync cache before reading
Both + total ordering