Sub topic 10
Non-Blocking Waits with Atomics.waitAsync
This chapter assumes you already know how Atomics.wait and Atomics.notify work from the previous chapter. You should also be comfortable with Promises and async/await, and know how to pass a SharedArrayBuffer to a worker.
Atomics.wait puts the calling thread to sleep. That is fine in a worker, which has no user interface to keep responsive. On the browser main thread, it is not allowed at all: calling Atomics.wait there throws a TypeError. Some threads in Node.js should not block either, such as the main thread of a server that handles requests on its event loop. Atomics.waitAsync fills this gap. It waits on a shared memory slot the same way Atomics.wait does, but it returns a Promise and the thread keeps running.
The Signature and Its Two Result Shapes
Atomics.waitAsync(typedArray, index, value, timeout)The arguments match Atomics.wait:
typedArraymust be anInt32ArrayorBigInt64Arraybacked by aSharedArrayBuffer. Any other array throws aTypeError.indexis the slot to watch.valueis the value you expect the slot to hold. The engine only waits if the slot still holds this value.timeoutis in milliseconds and is optional. It defaults toInfinity.
The return value is the part that catches people. It is not a Promise. It is a plain object { async, value }, and its shape depends on whether a wait actually started.
| Situation | `async` | `value` |
|---|---|---|
| Slot does not hold `value` | `false` | `'not-equal'` (a string) |
| Slot holds `value`, `timeout` is 0 | `false` | `'timed-out'` (a string) |
| Slot holds `value`, `timeout` greater than 0 | `true` | Promise resolving to `'ok'` or `'timed-out'` |
The synchronous cases exist so the engine does not create a Promise when it can answer immediately. Your code has to handle both shapes.
A Responsive Main Thread That Waits on a Worker
The following Node.js program runs as a single file. The main thread waits for a flag without blocking, and a timer keeps printing to show that the event loop is still running. The worker sets the flag after 100 ms and notifies.
const { Worker, isMainThread, workerData } = require('node:worker_threads');
if (isMainThread) {
const flag = new Int32Array(new SharedArrayBuffer(4));
new Worker(__filename, { workerData: flag.buffer });
const result = Atomics.waitAsync(flag, 0, 0);
console.log('async:', result.async); // true
const timer = setInterval(() => console.log('main thread still running'), 20);
result.value.then((outcome) => {
clearInterval(timer);
console.log(outcome, Atomics.load(flag, 0)); // ok 1
});
} else {
const flag = new Int32Array(workerData);
setTimeout(() => {
Atomics.store(flag, 0, 1);
Atomics.notify(flag, 0);
}, 100);
}Run it with node waitasync-demo.js. You will see about four "still running" lines, then ok 1. If you replaced waitAsync with Atomics.wait, the interval would not fire until the wait ended.
The worker's code did not change at all. Atomics.notify wakes synchronous and asynchronous waiters alike. Both kinds join the same first-in, first-out queue for that slot, and the count that notify returns includes both.
What Happens Inside
When a wait starts, the engine records a waiter for that slot, and that waiter belongs to the calling agent. No thread sleeps. When another agent calls Atomics.notify, or the timeout expires, the engine removes the waiter from the queue and schedules a task on the waiting agent's event loop. That task resolves the Promise.
This design has three consequences.
- Resolution is late. The waiter's thread has to finish its current task before the Promise settles. If the main thread runs a long synchronous computation, the wake-up waits for it to end.
- The value may have changed again. Between the notify and your
thencallback, other threads can write to the slot more times.'ok'only tells you that a notify happened. It does not tell you what the slot holds now, so always read it again withAtomics.load. - Notify has no memory. If the notify happens before you call
waitAsync, nobody is woken. The expected-value check protects you here: if the slot already changed, you get'not-equal'immediately instead of waiting forever.
A Reusable Helper
Raw waitAsync calls are easy to get wrong because of the two result shapes and the stale-value problem. Wrap them in a loop that rechecks the slot and keeps track of the overall deadline:
async function waitForChange(i32, index, expected, timeoutMs = Infinity) {
const deadline = performance.now() + timeoutMs;
while (Atomics.load(i32, index) === expected) {
const remaining = deadline - performance.now();
if (remaining <= 0) return 'timed-out';
const { async, value } = Atomics.waitAsync(i32, index, expected, remaining);
const outcome = async ? await value : value;
if (outcome === 'timed-out') return 'timed-out';
}
return 'ok';
}The loop handles a wake-up that arrives while the slot still holds expected. That happens when another thread calls notify without changing the value, or changes it and then changes it back. 'not-equal' simply ends the loop on the next check.
Waiting on a Sequence Number, Not a Boolean
A flag that flips from 0 to 1 works once. A worker that produces results repeatedly needs a value that never repeats. A common pattern is a sequence counter that the worker increments with Atomics.add after each result. The main thread remembers the last value it saw and waits for the counter to move past it.
// main thread
const seq = new Int32Array(new SharedArrayBuffer(4));
const worker = new Worker('producer.js');
worker.postMessage(seq.buffer);
async function consume() {
let seen = 0;
for (;;) {
await waitForChange(seq, 0, seen);
const current = Atomics.load(seq, 0);
console.log(`${current - seen} new result(s)`);
seen = current;
}
}
consume();
// producer.js
self.onmessage = (event) => {
const seq = new Int32Array(event.data);
setInterval(() => {
Atomics.add(seq, 0, 1);
Atomics.notify(seq, 0);
}, 50);
};Because the consumer compares against seen, it never misses an update. If the worker increments three times before the consumer wakes, the consumer reports three results in one pass.
Timeouts and Edge Cases
timeoutof 0 returns{ async: false, value: 'timed-out' }when the slot matches. This gives you a cheap way to ask "does this slot still hold X?" without a Promise, butAtomics.loadis clearer for that.- Negative or
NaNtimeouts count as 0.NaNis treated asInfinityinAtomics.wait, and asInfinityhere as well. Pass explicit numbers so you never depend on these rules. - No cancellation. There is no API to cancel a pending
waitAsync. To give up early, either use a timeout or have the other side write a value and callnotify. - Many pending waiters. Every call adds an entry to the slot's waiter queue. If you start waits in a loop without awaiting them, you leak waiters until they time out.
notify(slot, 1)with mixed waiters wakes whichever waiter has been queued longest. That may be a blocked worker rather than your async waiter.
Choosing Between wait and waitAsync
| Question | `Atomics.wait` | `Atomics.waitAsync` |
|---|---|---|
| Blocks the thread? | Yes | No |
| Allowed on browser main thread? | No, throws `TypeError` | Yes |
| Wake-up latency | Immediate on notify | After the current task finishes |
| Result type | String | `{ async, value }` |
| Good for | Worker loops, locks inside workers | UI threads, servers, mixing waits with other async work |
A worker that does nothing except process a queue should use Atomics.wait, because it wakes faster and is simpler. Use waitAsync on any thread that also has to handle events, timers, or I/O.
Exercise
A developer writes const outcome = await Atomics.waitAsync(flag, 0, 0); if (outcome === 'ok') render(); and render() never runs, even after the worker notifies. Why, and what is the fix?
Show answer
waitAsync returns a plain object { async, value }, not a Promise, so await produces that object immediately, and it never equals the string 'ok'. Destructure the result and await value only when async is true: const { async, value } = Atomics.waitAsync(flag, 0, 0); const outcome = async ? await value : value;.
Exercise
The main thread calls Atomics.waitAsync(seq, 0, 5) and the Promise resolves with 'ok'. The code then assumes seq[0] is 6. Give two reasons why it might not be.
Show answer
First, the worker may have incremented again, to 7 or more, before the resolution task ran on the main thread's event loop. Second, a thread may have called Atomics.notify without changing the slot, so it could still be 5. Always reread with Atomics.load and loop if the value still equals the expected one.
Exercise
Why does Atomics.waitAsync(flag, 0, 0, 0) return a string instead of a Promise when flag[0] is 0?
Show answer
A timeout of 0 means the wait would expire immediately, so the engine answers synchronously with { async: false, value: 'timed-out' } instead of creating a Promise and scheduling a task.