Sub topic 2
Why Plain Reads and Writes Race
This chapter assumes you can create a SharedArrayBuffer, wrap it in an Int32Array, and start Node.js worker_threads.
Why Plain Reads and Writes Race
counter[0]++ looks like a single step, but it runs as three: read the value, add one, and write the result back. When two threads run those steps at the same moment, both can read the same old value, and one of the increments is lost. Unsynchronized access like this is called a data race. Each run can give a different result.
Atomic Load, Store, and Read-Modify-Write Operations
The Atomics methods run each read-modify-write as one step that no other thread can split. Atomics.add, sub, and, or, xor, and exchange each return the old value. Atomics.load and Atomics.store handle plain reads and writes. They also put accesses in a sequentially consistent order, so a value one thread stores becomes visible to the others.
const { Worker, isMainThread, workerData } = require('node:worker_threads');
if (isMainThread) {
const counter = new Int32Array(new SharedArrayBuffer(4));
let done = 0;
for (let i = 0; i < 4; i++) {
new Worker(__filename, { workerData: counter.buffer }).on('exit', () => {
if (++done === 4) console.log(Atomics.load(counter, 0)); // always 400000
});
}
} else {
const counter = new Int32Array(workerData);
for (let i = 0; i < 100000; i++) Atomics.add(counter, 0, 1);
}If you replace Atomics.add(counter, 0, 1) with counter[0]++, the total often comes out below 400000.
Compare-and-Swap with Atomics.compareExchange
Atomics.compareExchange(ta, i, expected, replacement) writes replacement only if the slot still holds expected. Either way, it returns the value the slot held before the call. You can build any atomic update by retrying it in a loop:
function atomicMax(i32, index, value) {
let current = Atomics.load(i32, index);
while (value > current) {
const previous = Atomics.compareExchange(i32, index, current, value);
if (previous === current) return; // our write won
current = previous; // another thread changed it; retry
}
}Blocking and Waking Threads with Atomics.wait and Atomics.notify
Atomics.wait(ta, i, expected) puts the thread to sleep, but only if the slot equals expected. It returns 'ok', 'not-equal', or 'timed-out'. Atomics.notify(ta, i, count) wakes up to count threads that are waiting on that slot. Both methods work only on an Int32Array or BigInt64Array backed by shared memory.
const { Worker, isMainThread, workerData, parentPort } = require('node:worker_threads');
if (isMainThread) {
const flag = new Int32Array(new SharedArrayBuffer(4));
new Worker(__filename, { workerData: flag.buffer })
.on('message', (result) => console.log(result)); // 'ok' (or 'not-equal' if the worker started late)
setTimeout(() => {
Atomics.store(flag, 0, 1);
Atomics.notify(flag, 0, 1);
}, 100);
} else {
const flag = new Int32Array(workerData);
parentPort.postMessage(Atomics.wait(flag, 0, 0));
}Exercise
Why does Atomics.wait take an expected value instead of always sleeping?
Show answer
The expected value closes a gap. The other thread might change the value and call notify after you check the value but before you sleep. If you always slept, you would miss that wake-up. Atomics.wait checks the value and starts sleeping in one atomic step, and it returns 'not-equal' at once if the value has already changed.
Exercise
Atomics.compareExchange(a, 0, 3, 9) returns 4. What does a[0] now hold?
Show answer
It holds 4. The slot did not equal 3, so nothing was written, and the call returned the current value.