Sub topic 12
Memory Ordering and the Happens-Before Guarantee
This chapter assumes you know how to share a SharedArrayBuffer between threads and how Atomics.store, Atomics.load, Atomics.wait, and Atomics.notify work. Here the question changes. Earlier chapters asked whether a single update is safe. This one asks when one thread's writes become visible to another thread, and in what order.
Why order is not guaranteed by default
Compilers and CPUs reorder memory operations to run faster. On a single thread you never notice, because the result looks the same. Another thread reading the same memory can notice. It might see a "ready" flag set before the data that flag announces has been written. A JIT compiler might also hoist a plain read out of a loop, so a loop like while (flag[0] === 0) {} could spin forever.
JavaScript's memory model handles this by giving different kinds of access different guarantees.
| Access kind | Example | Ordering guarantee |
|---|---|---|
| Plain read/write | `data[i] = 5` | None across threads. It may be reordered, merged, or torn if it races. |
| Atomic operation | `Atomics.store(flag, 0, 1)` | Sequentially consistent: all threads agree on one total order of atomic operations. |
The happens-before guarantee
You do not need to make every access atomic. Suppose thread A does plain writes and then an atomic store, and thread B does an atomic load that reads the value A stored. Then everything A wrote before the store happens before everything B does after the load. The atomic pair works like a gate. Plain writes cannot leak forward past it, and plain reads cannot be moved back before it.
This leads to the rule to remember. If every conflicting access is ordered by happens-before through atomics, the program has no data race, and it behaves as if all threads were interleaved one step at a time (sequential consistency).
Publishing data safely
This Node.js script runs as written. The worker fills an array with plain writes and then publishes it with one atomic store.
const { Worker, isMainThread, workerData } = require('node:worker_threads');
if (isMainThread) {
const sab = new SharedArrayBuffer(4 + 4 * 4);
const flag = new Int32Array(sab, 0, 1);
const data = new Int32Array(sab, 4, 4);
new Worker(__filename, { workerData: sab });
while (Atomics.load(flag, 0) === 0) {
Atomics.wait(flag, 0, 0); // Node's main thread is allowed to block
}
console.log(Array.from(data)); // [ 10, 20, 30, 40 ]
} else {
const flag = new Int32Array(workerData, 0, 1);
const data = new Int32Array(workerData, 4, 4);
for (let i = 0; i < data.length; i++) {
data[i] = (i + 1) * 10; // plain writes
}
Atomics.store(flag, 0, 1); // publish: earlier writes happen before this
Atomics.notify(flag, 0);
}The while loop re-checks the flag with Atomics.load. That load is the acquiring side of the gate, and it also covers the case where the worker finished before the main thread began waiting.
Common mistakes
- Making only the writer side atomic. Both sides need an atomic operation on the same location.
- Synchronizing on different locations. A store to
flag[0]followed by a load offlag[1]orders nothing. - Writing data after the publishing store. The guarantee covers only writes made before the store.
Exercise
A worker writes result[0] = 99 (plain), then runs Atomics.store(ready, 0, 1). The main thread reads ready[0] with a plain read, sees 1, and then reads result[0]. Is it guaranteed to see 99? Why or why not?
Show answer
No. Happens-before needs an atomic store paired with an atomic load that reads the stored value. The plain read of ready[0] is a data race and creates no ordering, so result[0] could still read 0. Use Atomics.load(ready, 0) to make the guarantee hold.