Full answer
Plain reads and writes on shared memory are not atomic as a group. counter = counter + 1 reads, adds, and writes, so two threads can overwrite each other's update. A mutex makes the sequence exclusive.
Lock design (three states, in one Int32 slot):
- 0: free.
- 1: locked, nobody is waiting.
- 2: locked, and at least one thread may be sleeping.
lock():
- Try Atomics.compareExchange(a, i, 0, 1). If it returns 0, you own the lock.
- Otherwise mark the lock as contended (state 2) and call Atomics.wait(a, i, 2), which sleeps while the value is still 2. When woken, try again to take it with state 2.
release():
- Atomics.sub(a, i, 1). If the old value was 1, nobody waits and the lock is free. If it was 2, store 0 and call Atomics.notify(a, i, 1) to wake one waiter.
Why the third state exists: it avoids calling notify when there are no waiters, which keeps the uncontended path cheap.
Waiting without blocking:
- Atomics.wait stops the whole thread. In a worker that is fine. In the main thread of a server it freezes the event loop. Browsers forbid it on the main thread, Node allows it, but you should not use it there.
- Atomics.waitAsync(a, i, expected) returns { async, value }. When async is true, value is a promise that resolves to 'ok' after notify, or 'timed-out'. It does not block.
Notes: wait returns 'ok', 'not-equal' or 'timed-out'. Keep critical sections short. A thread that dies while holding the lock leaves it locked forever, so avoid throwing inside the section (use try/finally). In most programs message passing or a queue is simpler than shared memory locks.
const { Worker, isMainThread, workerData } = require('node:worker_threads');
class Mutex {
constructor(view, index) { this.view = view; this.index = index; }
lock() {
const { view: a, index: i } = this;
let state = Atomics.compareExchange(a, i, 0, 1);
if (state !== 0) {
do {
if (state === 2 || Atomics.compareExchange(a, i, 1, 2) !== 0) Atomics.wait(a, i, 2);
} while ((state = Atomics.compareExchange(a, i, 0, 2)) !== 0);
}
}
release() {
const { view: a, index: i } = this;
if (Atomics.sub(a, i, 1) !== 1) {
Atomics.store(a, i, 0);
Atomics.notify(a, i, 1);
}
}
}
const THREADS = 4;
const ROUNDS = 50000;
const UNSAFE_ROUNDS = 500000;
if (!isMainThread) {
const view = new Int32Array(workerData.buffer); // [0] lock, [1] unsafe counter, [2] safe counter, [3] start gate
const mutex = new Mutex(view, 0);
Atomics.wait(view, 3, 0); // all workers start together
for (let n = 0; n < UNSAFE_ROUNDS; n++) view[1] = view[1] + 1; // no protection
for (let n = 0; n < ROUNDS; n++) {
mutex.lock();
try { view[2] = view[2] + 1; } finally { mutex.release(); } // protected
}
} else {
(async () => {
const buffer = new SharedArrayBuffer(16);
const view = new Int32Array(buffer);
const workers = Array.from({ length: THREADS }, () => new Worker(__filename, { workerData: { buffer } }));
await Promise.all(workers.map((w) => new Promise((resolve) => w.once('online', resolve))));
Atomics.store(view, 3, 1);
Atomics.notify(view, 3); // open the gate
await Promise.all(workers.map((w) => new Promise((resolve) => w.once('exit', resolve))));
const expected = THREADS * ROUNDS;
console.log('expected total for the protected counter:', expected);
console.log('protected counter:', view[2], '| exact:', view[2] === expected);
console.log('unprotected counter lost updates:', view[1] < THREADS * UNSAFE_ROUNDS);
// wait() with a timeout, and waitAsync() that does not block the event loop.
const flag = new Int32Array(new SharedArrayBuffer(4));
console.log('Atomics.wait on an unchanged value for 10 ms:', Atomics.wait(flag, 0, 0, 10));
console.log('Atomics.wait when the value differs:', Atomics.wait(flag, 0, 1, 10));
const waiting = Atomics.waitAsync(flag, 0, 0);
setTimeout(() => Atomics.notify(flag, 0), 10);
console.log('waitAsync is async:', waiting.async, '| result:', await waiting.value);
})();
}Four workers start together and increment two counters, one with the mutex and one without. The protected total is exact and the unprotected one loses updates. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): expected total for the protected counter: 200000 protected counter: 200000 | exact: true unprotected counter lost updates: true Atomics.wait on an unchanged value for 10 ms: timed-out Atomics.wait when the value differs: not-equal waitAsync is async: true | result: ok
Key points
- Shared counters need atomic or locked updates.
- A three-state lock avoids needless notify calls.
- Atomics.wait sleeps the thread until notify or timeout.
- Use Atomics.waitAsync where blocking is not allowed.
- Release in finally, and prefer message passing when possible.
Common mistakes
- Using counter++ on shared memory without Atomics or a lock.
- Calling Atomics.wait on the main thread of a server.
- Holding the lock while doing slow work or throwing without finally.
- Using a two-state lock and calling notify on every release.
- Using shared memory when a message queue would be simpler.
Follow-ups
- What does Atomics.wait return, and when?
- Why can a lock held by a crashed worker be a problem?
- How would you build a semaphore from the same pieces?
Tips
- Draw the three states as 0, 1, 2.
- Say that waitAsync exists for the main thread.
- Admit that message passing is simpler.