Sub topic 9
Blocking and Waking Threads with Atomics.wait and Atomics.notify
So far, a thread that needs a value from another thread has had two options. It can poll the shared slot with Atomics.load in a loop, which burns CPU, or it can wait for a postMessage, which brings back the cost of messaging. Atomics.wait and Atomics.notify add a third option. A thread sleeps until a particular memory slot changes, and the thread that changes it wakes the sleeper.
This chapter assumes you know how to share a SharedArrayBuffer with a worker, how to read and write it through an Int32Array, and how Atomics.load and Atomics.store work. Non-blocking waits (Atomics.waitAsync) and full locks are covered in later chapters.
The Two Calls
Atomics.wait(typedArray, index, expectedValue, timeout) puts the calling thread to sleep, but only if typedArray[index] still equals expectedValue at the moment of the call. The check and the decision to sleep happen as one indivisible step.
Atomics.notify(typedArray, index, count) wakes up to count threads sleeping on that same slot and returns how many it woke. If you leave out count, it wakes all of them.
| Argument | `Atomics.wait` | `Atomics.notify` |
|---|---|---|
| `typedArray` | `Int32Array` or `BigInt64Array` over a `SharedArrayBuffer` | Same types; on a non-shared buffer it just returns 0 |
| `index` | Slot to watch | Slot whose waiters to wake |
| third argument | Value you expect to find there | Maximum number of waiters to wake (default `+Infinity`) |
| `timeout` | Milliseconds, default `Infinity` | Not applicable |
| Returns | `"ok"`, `"not-equal"`, or `"timed-out"` | Number of threads woken |
Waiters are keyed by buffer and byte position, so two different Int32Array views that point at the same bytes refer to the same slot. A notify on index 0 never wakes a waiter on index 1.
What the Return Values Mean
| Value | Meaning |
|---|---|
| `"not-equal"` | The slot did not hold `expectedValue` when you called, so the thread never slept |
| `"ok"` | The thread slept and was woken by `Atomics.notify` |
| `"timed-out"` | The thread slept and the timeout ran out before any notify |
A common mistake is to treat "ok" as "the value changed." It only means somebody called notify on that slot. The notifier may not have changed the value, or another thread may have changed it back before your thread ran again. Always re-check the condition after waking.
Why the Check and the Sleep Must Be Atomic
Imagine a naive version where the worker reads the flag, sees 0, and then goes to sleep. If the main thread sets the flag and calls notify between the read and the sleep, the notify finds nobody waiting. The worker then sleeps forever. This is called a lost wakeup.
Atomics.wait avoids it because the comparison and the move into the waiter list happen together, protected by a lock inside the engine. One of two orders is possible. Either the store lands first, so wait sees a different value and returns "not-equal", or the worker is already in the waiter list when notify runs and gets woken.
The Standard Pattern: Wait in a Loop
Since "ok" does not prove the condition holds, the correct shape is a loop that checks the condition, waits while it is false, and checks again. Save this as wait-notify.js and run it with node wait-notify.js:
const { Worker, isMainThread, workerData, parentPort } = require('node:worker_threads');
const READY = 0; // index of the ready flag
const PAYLOAD = 1; // index of the data the worker needs
if (isMainThread) {
const state = new Int32Array(new SharedArrayBuffer(8));
const worker = new Worker(__filename, { workerData: state.buffer });
worker.on('message', (msg) => {
console.log('worker says:', msg);
worker.terminate();
});
setTimeout(() => {
Atomics.store(state, PAYLOAD, 99); // write the data first
Atomics.store(state, READY, 1); // then publish it
const woken = Atomics.notify(state, READY, 1);
console.log('notify woke', woken, 'waiter(s)');
}, 200);
} else {
const state = new Int32Array(workerData);
while (Atomics.load(state, READY) === 0) {
Atomics.wait(state, READY, 0);
}
parentPort.postMessage(`payload = ${Atomics.load(state, PAYLOAD)}`);
}Typical output:
notify woke 1 waiter(s)
worker says: payload = 99If the worker starts slowly, you may see notify woke 0 waiter(s) instead. The program is still correct, because the worker checks READY before it waits and finds it already set. A count of 0 tells you something about timing. It does not mean the program failed.
The order of the writes matters. The payload is stored before the flag, and both use Atomics, so a worker that sees READY === 1 is guaranteed to see PAYLOAD === 99. The chapter on memory ordering explains why that guarantee holds.
Timeouts
The fourth argument is a time limit in milliseconds. Fractions are allowed, NaN is treated as Infinity, and negative values act as 0. A wait on a slot that nobody ever notifies gives you a synchronous sleep, which some worker code uses as a cheap back-off:
function sleep(ms) {
const slot = new Int32Array(new SharedArrayBuffer(4));
return Atomics.wait(slot, 0, 0, ms); // always 'timed-out'
}
const start = Date.now();
console.log(sleep(50), Date.now() - start >= 50); // timed-out trueWhen you combine a timeout with the wait loop, a woken thread that finds the condition still false must not restart the full timeout. If it does, the total wait can grow without limit. Track a deadline instead:
function waitUntilNonZero(i32, index, timeoutMs) {
const deadline = Date.now() + timeoutMs;
while (Atomics.load(i32, index) === 0) {
const remaining = deadline - Date.now();
if (remaining <= 0) return false;
Atomics.wait(i32, index, 0, remaining);
}
return true;
}
const slot = new Int32Array(new SharedArrayBuffer(4));
console.log(waitUntilNonZero(slot, 0, 30)); // false after about 30 msWaking One Thread or Many
count controls how many sleepers wake, and the engine wakes them in the order they started waiting.
- Use
Atomics.notify(arr, i, 1)when only one thread can use the event, for example one new item in a work queue. Waking all of them makes most wake up, find nothing, and go back to sleep. This is the "thundering herd" problem. - Use
Atomics.notify(arr, i)(all waiters) when every waiter cares, such as a "shutdown" flag or a barrier where all threads continue together.
A notify affects only threads that are already waiting. It is not saved for later. That is why the shared value, not the notify, has to carry the state.
Where You Are Allowed to Block
Atomics.wait blocks the thread completely, so its event loop stops too. Engines restrict where you can call it.
| Context | `Atomics.wait` allowed? | Effect |
|---|---|---|
| Browser main thread | No, throws `TypeError` | Blocking would freeze the page |
| Dedicated Web Worker | Yes | The worker's message handlers stop until it wakes |
| Node.js worker thread | Yes | That worker's event loop is paused |
| Node.js main thread | Yes | Timers, I/O, and callbacks all stop |
Atomics.notify never blocks, so you can call it anywhere, including the browser main thread. The usual setup is that the main thread notifies and workers wait.
The call also throws a TypeError if the array is not an Int32Array or BigInt64Array, or if it views a plain ArrayBuffer. A Uint32Array or Float64Array is rejected even when it is shared.
Common Errors
- Waiting without a loop. One
"ok"does not prove the condition holds. Wrap the wait in awhilethat re-checks the condition. - Changing the value with a plain write.
state[0] = 1followed bynotifymay not make the new value visible in a well-ordered way. UseAtomics.storeor a read-modify-write operation. - Notifying a different slot. Waiter and notifier must use the same buffer and the same byte position.
- Passing the wrong expected value. If you expect 0 but the idle state is -1, every call returns
"not-equal"and the loop becomes a busy spin. - Relying on notify counts for correctness. A return of 0 is normal when the waiter has not reached
waityet.
Exercise
A worker runs Atomics.wait(flag, 0, 0) and gets "not-equal" straight away. The main thread's Atomics.notify(flag, 0) returned 0. Is there a bug, and what happened?
Show answer
There is no bug. The main thread stored a non-zero value and called notify before the worker reached its wait. Nobody was waiting, so notify returned 0. The worker's wait saw that flag[0] was no longer 0 and returned "not-equal" without sleeping. The value in the slot carried the state, so no wakeup was lost.
Exercise
Four workers sleep on jobs[0] waiting for work. The main thread adds a single job and calls Atomics.notify(jobs, 0). What problem does this cause, and how do you fix it?
Show answer
Leaving out count wakes all four workers. Only one can take the job, so the other three wake, find nothing, and go back to sleep. That wastes CPU (the thundering herd problem). Call Atomics.notify(jobs, 0, 1) to wake exactly one worker per job. The workers must still re-check the job count in a loop after waking.
Exercise
Why does this helper risk waiting much longer than 100 ms? while (Atomics.load(a, 0) === 0) Atomics.wait(a, 0, 0, 100);
Show answer
Every time the thread wakes and finds the value still 0, the next wait gets a fresh 100 ms. Repeated notifies that do not change the value can extend the total wait without limit. Compute a deadline once and pass the remaining time (deadline minus now) to each wait. Stop when the remaining time is zero or less.