Sub topic 9
Blocking and Waking Threads with Atomics.wait and Atomics.notify
This chapter assumes you know how to share a SharedArrayBuffer between threads, how to read and write it through an Int32Array, and how Atomics.load and Atomics.store work.
Atomic operations make each read and write safe. They do not let a thread wait for something to happen. You could spin in a loop that calls Atomics.load until a value changes, but that keeps a CPU core at 100% doing nothing useful. Atomics.wait and Atomics.notify let a thread sleep until another thread wakes it.
The working model
Atomics.wait(i32, index, expected, timeout) does two things as one indivisible step:
- It checks whether
i32[index]still equalsexpected. - If it does, the thread goes to sleep on that memory slot. If it does not, the call returns immediately.
Because the check and the sleep cannot be split, no other thread can change the value between them. This prevents the "lost wakeup" bug, where a thread misses a notification that arrives just before it falls asleep.
Atomics.notify(i32, index, count) wakes up to count threads sleeping on that slot and returns how many it woke. If you leave out count, it wakes all of them.
| `Atomics.wait` returns | Meaning |
|---|---|
| `"ok"` | The thread slept and was woken by `Atomics.notify` |
| `"not-equal"` | The value already differed from `expected`, so it never slept |
| `"timed-out"` | The timeout in milliseconds expired before any notify |
A runnable example
This Node.js script runs in one file. The worker sleeps until the main thread sets a flag.
const { Worker, isMainThread, workerData, parentPort } = require('node:worker_threads');
if (isMainThread) {
const flag = new Int32Array(new SharedArrayBuffer(4));
const worker = new Worker(__filename, { workerData: flag.buffer });
worker.on('message', (result) => {
console.log('worker result:', result); // usually 'ok'
worker.terminate();
});
setTimeout(() => {
Atomics.store(flag, 0, 1); // change the value first
const woken = Atomics.notify(flag, 0, 1); // then wake one waiter
console.log('threads woken:', woken); // usually 1
}, 100);
} else {
const flag = new Int32Array(workerData);
const result = Atomics.wait(flag, 0, 0); // sleep while flag[0] === 0
parentPort.postMessage(result);
}If the worker starts slowly and the main thread stores 1 first, you will see threads woken: 0 and worker result: not-equal. That result is still correct. The worker saw the new value and did not sleep, so no wakeup was lost.
Common errors
- Waiting on the browser main thread. Browsers do not allow the main thread to block, so
Atomics.waitthrows aTypeErrorthere. Use it only in workers. Node.js allows it on the main thread, but doing so freezes the event loop. - Wrong array type.
waitandnotifyonly work on anInt32ArrayorBigInt64Array.waitalso needs that array to view aSharedArrayBuffer. - Notify before store. If you notify first and change the value afterward, a woken thread can re-check, still see the old value, and go back to sleep. Always change the value, then notify.
- Treating "ok" as proof of the condition. Another thread may change the value again before the woken thread runs. Check the value in a loop:
while (Atomics.load(flag, 0) === 0) {
Atomics.wait(flag, 0, 0);
}Exercise
A worker calls Atomics.wait(flag, 0, 0, 500) while flag[0] is 3. What does the call return, and does the worker sleep?
Show answer
It returns "not-equal" immediately and never sleeps, because the slot does not hold the expected value 0. The 500 ms timeout is never used.
Exercise
Three workers are waiting on flag[0]. The main thread calls Atomics.notify(flag, 0) with no count. How many workers wake, and what does notify return?
Show answer
All three wake, because leaving out count means wake every waiter. Notify returns 3.