Full answer
Normally workers share nothing and exchange copies. A SharedArrayBuffer is different: the same memory is visible to the main thread and every worker that receives it, so reads and writes by one thread are seen by the others. This enables fast parallel algorithms, but it also brings the usual concurrency problems.
The classic problem is a lost update. The statement counter[0]++ is three steps: read, add one, write. Two threads can both read 5, both write 6, and one increment disappears. The result changes from run to run, which makes the bug hard to find.
Atomics provides operations on integer typed arrays that happen as one indivisible step. Atomics.add(view, index, value) increases a value without interleaving. Atomics.load and Atomics.store give ordered, safe reads and writes. Atomics.compareExchange sets a value only if it still holds an expected one, which is the building block for locks. Atomics.wait(view, index, expected) blocks a thread until another thread calls Atomics.notify(view, index), so a thread can sleep without spinning in a loop. Atomics.wait is not allowed on the browser main thread, where Atomics.waitAsync is available instead.
Shared memory has one more requirement in browsers. Since the Spectre attacks, SharedArrayBuffer is only available on pages that are cross-origin isolated, which means serving them with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp headers. Node.js has no such restriction.
Use shared memory only when copying is too slow, for example for large numeric arrays, WebAssembly threads, or lock-free queues. Message passing is simpler and safer for most programs.
const { Worker } = require('node:worker_threads');
const workerSource = `
const { parentPort, workerData } = require('node:worker_threads');
const view = new Int32Array(workerData.buffer);
const { mode, rounds } = workerData;
if (mode === 'atomic') {
for (let i = 0; i < rounds; i++) Atomics.add(view, 0, 1);
parentPort.postMessage('done');
} else if (mode === 'plain') {
for (let i = 0; i < rounds; i++) view[1] = view[1] + 1;
parentPort.postMessage('done');
} else if (mode === 'wait') {
Atomics.wait(view, 2, 0); // sleep while the flag at index 2 is still 0
parentPort.postMessage('woken, flag is ' + Atomics.load(view, 2));
}
`;
const run = (buffer, mode, rounds = 0) =>
new Promise((resolve, reject) => {
const worker = new Worker(workerSource, { eval: true, workerData: { buffer, mode, rounds } });
worker.once('message', resolve);
worker.once('error', reject);
});
(async () => {
const buffer = new SharedArrayBuffer(16);
const view = new Int32Array(buffer);
const workers = 4;
const rounds = 100000;
await Promise.all(Array.from({ length: workers }, () => run(buffer, 'atomic', rounds)));
console.log('atomic counter:', Atomics.load(view, 0), 'expected:', workers * rounds);
await Promise.all(Array.from({ length: workers }, () => run(buffer, 'plain', rounds)));
const plain = Atomics.load(view, 1);
console.log('plain counter never exceeds the expected value:', plain <= workers * rounds);
let finished = false;
const sleeper = run(buffer, 'wait').then((message) => {
finished = true;
return message;
});
await new Promise((resolve) => setTimeout(resolve, 50));
Atomics.store(view, 2, 7);
let woken = 0;
while (!finished) {
woken += Atomics.notify(view, 2); // returns how many sleeping threads were woken
await new Promise((resolve) => setTimeout(resolve, 5));
}
console.log('at most one worker was woken:', woken <= 1);
console.log(await sleeper);
console.log(Atomics.compareExchange(view, 3, 0, 42), view[3], Atomics.compareExchange(view, 3, 0, 99), view[3]);
console.log(buffer instanceof SharedArrayBuffer, buffer.byteLength);
})();Run with Node.js v24.22.1 as js-92.js; two runs gave identical output. Output: atomic counter: 400000 expected: 400000 plain counter never exceeds the expected value: true at most one worker was woken: true woken, flag is 7 0 42 42 42 true 16
Key points
- SharedArrayBuffer memory is visible to all threads that receive it.
- counter++ is read, add, write, so concurrent increments can be lost.
- Atomics operations (add, load, store, compareExchange) are indivisible.
- Atomics.wait and notify let a thread sleep until another thread signals; wait is not allowed on the browser main thread.
- Browsers require cross-origin isolation (COOP and COEP headers) for SharedArrayBuffer.
Common mistakes
- Using counter++ on shared memory and expecting a correct total.
- Calling Atomics.wait on the browser main thread, which throws.
- Forgetting the cross-origin isolation headers, so SharedArrayBuffer is undefined in the browser.
- Reaching for shared memory when message passing would be simpler.
Follow-ups
- How would you build a mutex with Atomics.compareExchange and Atomics.wait?
- What is Atomics.waitAsync, and why does the main thread need it?
- Why were SharedArrayBuffers disabled in browsers in 2018 and later re-enabled?
Tips
- Show the three steps of counter++ and the lost update; it makes the need for Atomics clear.
- Name compareExchange as the lock primitive and wait and notify for sleeping.
- Mention cross-origin isolation for the browser side.