Sub topic 6
Why Plain Reads and Writes Race
This chapter assumes you already know how to create a SharedArrayBuffer, wrap it in an Int32Array, and pass it to a Node.js worker thread. It explains what goes wrong when several threads touch the same memory with ordinary JavaScript reads and writes.
What a data race is
A data race happens when two threads access the same memory location at the same time, at least one of them writes, and nothing orders the accesses. With postMessage and a normal ArrayBuffer this cannot happen, because each thread gets its own copy. Shared memory removes the copy, so the race becomes possible.
Why `counter[0]++` is not one step
The expression counter[0]++ looks like a single action. The engine actually performs three:
- Read the current value from memory.
- Add one to it in a register.
- Write the result back to memory.
Another thread can run between any two of these steps. If two threads both read 5, both compute 6, and both write 6, one increment is gone. This is called a lost update.
Seeing the race happen
This Node.js program runs four workers. Each increments a shared counter 100,000 times with a plain ++.
const { Worker, isMainThread, workerData } = require('node:worker_threads');
const WORKERS = 4;
const ITERATIONS = 100000;
if (isMainThread) {
const counter = new Int32Array(new SharedArrayBuffer(4));
let finished = 0;
for (let i = 0; i < WORKERS; i++) {
const w = new Worker(__filename, { workerData: counter.buffer });
w.on('exit', () => {
if (++finished === WORKERS) {
console.log(`expected ${WORKERS * ITERATIONS}, got ${counter[0]}`);
}
});
}
} else {
const counter = new Int32Array(workerData);
for (let i = 0; i < ITERATIONS; i++) {
counter[0]++; // non-atomic read-modify-write
}
}Run it a few times. On a multi-core machine the result usually falls below 400,000 and changes from run to run. Sometimes it comes out right, and that makes this kind of bug hard to catch in testing.
Races beyond lost updates
Lost updates are the easiest race to see. Plain accesses cause two other problems:
| Problem | What you observe |
|---|---|
| Stale reads | A worker loops on `while (flag[0] === 0) {}` and never exits, because the engine may keep the value in a register and never read memory again. |
| Reordering | One thread writes `data[0] = 42` and then `ready[0] = 1`. Another thread can see `ready[0] === 1` and still read the old `data[0]`. |
| Torn values | Accesses that are misaligned or wider than the hardware handles in one operation, such as `Float64Array` on some platforms, can return a mix of old and new bytes. |
The fix, in brief
The race exists because each step is separate and unordered. The next chapter introduces Atomics operations such as Atomics.add, Atomics.load, and Atomics.store. Each one does its read, modify, and write as a single indivisible step and orders it relative to other atomic accesses. Replacing counter[0]++ with Atomics.add(counter, 0, 1) makes the program above print 400,000 every time.
Exercise
Thread A runs buf[0] = buf[0] + 10 and thread B runs buf[0] = buf[0] * 2 on the same shared Int32Array, where buf[0] starts at 1. Neither uses Atomics. List every final value buf[0] can hold, and say which ones come from a lost update.
Show answer
22 (A then B: 11 * 2), 12 (B then A: 2 + 10), 11 (both read 1, B writes 2, A writes 11 last), and 2 (both read 1, A writes 11, B writes 2 last). The values 11 and 2 are lost updates, because each one keeps only one thread's change.
Exercise
A worker waits with while (flag[0] === 0) {} while the main thread sets flag[0] = 1. Why might the worker never stop, even though the write happened?
Show answer
A plain read is not synchronized, so the engine may hoist the load out of the loop and keep reusing the value it first read. The worker then never sees the write. An atomic load, or Atomics.wait, forces a fresh read that is ordered after the other thread's write.