Sub topic 6
Why Plain Reads and Writes Race
This chapter explains what goes wrong when two threads touch the same shared memory with ordinary JavaScript reads and writes. It assumes you can already create a SharedArrayBuffer, wrap it in an Int32Array, and hand it to a Node.js worker thread or a Web Worker. Those steps were covered in earlier chapters. The fix, the Atomics object, comes in the next chapter. Here the goal is to recognize the bug when you see it.
What a data race is
A data race happens when two agents access the same memory location at the same time, at least one of the accesses is a write, and neither access is atomic. An agent is a thread of JavaScript execution, such as the main thread or a worker.
Before SharedArrayBuffer, JavaScript had no data races. Each agent had its own heap, and postMessage copied or transferred data, so only one agent could ever see a given byte. Shared memory removes that guarantee. Once two workers hold views onto the same buffer, every plain shared[i] = x and shared[i] read can conflict.
Three kinds of failure follow from data races:
| Failure | What you observe | Typical cause |
|---|---|---|
| Lost update | A counter ends up lower than expected | Two read-modify-write sequences interleave |
| Stale or reordered read | A reader sees a "ready" flag but old data | Writes become visible in a different order |
| Hoisted read | A spin loop never exits | The compiler reads the value once and reuses it |
| Torn read | A value that no thread ever wrote | A multi-byte access is split into smaller pieces |
Lost updates: `counter[0]++` is three steps
The expression counter[0]++ looks like one operation, but the engine runs it as three:
- Load the current value from memory into a register.
- Add 1 to the register.
- Store the register back to memory.
If two threads run these steps at the same time, both can load the same old value, both add 1, and both store the same result. One increment disappears.
You can watch this happen. The Node.js program below starts four workers. Each one increments a shared counter 100,000 times with plain ++. Save it as race.js and run node race.js.
const { Worker, isMainThread, workerData } = require('node:worker_threads');
const WORKERS = 4;
const ITERATIONS = 100000;
if (isMainThread) {
const sab = new SharedArrayBuffer(4);
const counter = new Int32Array(sab);
let finished = 0;
for (let i = 0; i < WORKERS; i++) {
const w = new Worker(__filename, { workerData: sab });
w.on('exit', () => {
if (++finished === WORKERS) {
console.log('expected:', WORKERS * ITERATIONS);
console.log('actual: ', counter[0]);
}
});
}
} else {
const counter = new Int32Array(workerData);
for (let i = 0; i < ITERATIONS; i++) {
counter[0]++; // plain read-modify-write: races with other workers
}
}On a multi-core machine the actual total usually comes out well below 400,000, and it changes from run to run. Sometimes it is correct, especially when the workers start at different moments and barely overlap. That inconsistency is what makes races dangerous. A test that passes once proves nothing.
Reordering: writes become visible out of order
A subtler race involves two separate locations. A common pattern is to write some data, then set a flag that says the data is ready:
// worker A (producer)
data[0] = 123;
flag[0] = 1;
// worker B (consumer)
if (flag[0] === 1) {
console.log(data[0]); // may print 0, not 123
}It seems that if B sees flag[0] === 1, the write to data[0] must already have happened. With plain accesses, nothing guarantees that. Two layers can reorder the operations:
- The JIT compiler may reorder independent stores or loads when it optimizes, because from a single thread's point of view the order makes no difference.
- The CPU may make stores visible to other cores in a different order than the program issued them. ARM processors do this regularly. x86 does it less, but it still allows some reorderings.
For plain accesses, the ECMAScript memory model promises nothing about what one agent observes of another agent's order. Atomic operations do come with that promise, and a later chapter covers it in detail.
Hoisting: a spin loop that never ends
Busy-waiting on a plain read is a classic mistake:
// worker B waits for worker A to set flag[0]
while (flag[0] === 0) {
// spin
}
console.log('flag changed');The loop body never writes to flag. An optimizing compiler is allowed to assume no other agent changes a non-atomic location, so it can read flag[0] once, see 0, and turn the loop into while (true) {}. The worker then hangs even after another thread sets the flag. Whether this happens depends on the engine and on how hot the loop gets. Because the spec allows it, the code is wrong either way.
Torn reads: values nobody wrote
A torn read occurs when a multi-byte value is read or written in pieces, so a reader gets half of an old value and half of a new one. The memory model rules this out for some accesses and allows it for others:
- Aligned accesses through integer typed arrays such as
Int32Arrayare tear-free. Typed array views are always aligned to their element size, so this case is common and safe from tearing, though it can still race in the other ways listed above. - 8-byte elements (
Float64Array,BigInt64Array) may tear on platforms without native 8-byte atomic hardware. DataViewaccesses, and anything at an unaligned offset, can tear.- A logical value spread across several elements always "tears" in practice. For example, an
{x, y}point stored in two slots can be read afterxis updated but beforeyis.
// writer updates a 2D point stored in two slots
point[0] = 10; // x
point[1] = 20; // y
// reader may observe x = 10, y = old value
const x = point[0];
const y = point[1];Atomics cannot make a two-slot update indivisible. Multi-field updates need a lock or a protocol that publishes a complete snapshot. Later chapters build both.
What JavaScript still guarantees
Races in JavaScript are much less severe than in C or C++. In C++, a data race is undefined behavior, and the compiler may do anything. The ECMAScript memory model is stricter:
- A racy program stays memory-safe. It cannot read outside the buffer or crash the engine.
- A racy read returns a value that some write could have produced. With tear-free accesses, that means a value that some agent actually stored, or the initial value.
- Code that does not touch the racy location is unaffected.
So the damage stays inside your data. You get wrong numbers, stale flags, or hung loops, but the engine itself never breaks.
Spotting races in code review
When you review code that uses a SharedArrayBuffer, check every access to a shared view with these questions:
- Can another agent write this location while this code reads or writes it?
- Is this a read-modify-write, such as
++,+=,|=, orx = x + ...? If so, it can lose updates. - Does correctness depend on one write becoming visible before another? If so, plain stores give no ordering guarantee.
- Does a loop wait for a value that only another agent changes? If so, the compiler may hoist the read.
- Does a logical value span more than one element, or use
DataViewor 8-byte types? If so, readers can see a mix of old and new.
A "yes" to the first question plus any other "yes" means you need Atomics or a lock.
Exercise
Two workers share an Int32Array named stats. Each worker runs stats[0] += batch.length after processing a batch. The totals come out too low under load but correct in unit tests that use one worker. Explain why, and name which category of race this is.
Show answer
stats[0] += batch.length is a read-modify-write: it loads stats[0], adds, then stores. When both workers load the same old value before either stores, one addition overwrites the other, so the total is too low. This is a lost update. With only one worker nothing overlaps, so unit tests never see it.
Exercise
A worker runs while (ready[0] === 0) {} and then reads result[0]. The main thread sets result[0] = 99 and then ready[0] = 1 with plain assignments. List two distinct ways this code can misbehave.
Show answer
First, the JIT may hoist the read of ready[0] out of the loop, so the worker spins forever even after ready[0] becomes 1. Second, even if the loop exits, the store to result[0] is not guaranteed to be visible before the store to ready[0], so the worker may read a stale value (such as 0) instead of 99.
Exercise
Is a read of a Float64Array element shared between workers guaranteed to return a value that some worker actually wrote? What about an Int32Array element?
Show answer
For Int32Array, yes: aligned integer typed array accesses are tear-free, so the read returns some value that was written (or the initial value), though it may be stale. For Float64Array, no: 8-byte accesses may tear on platforms without 8-byte atomic support, so the read could combine bytes from two different writes.