Wait and notify with Atomics
Wait and notify with Atomics in Node.js 24: a worker sleeps on Atomics.wait until the main thread stores a value and calls Atomics.notify.
A worker that has nothing to do should sleep, not spin in a loop checking a flag. Atomics.wait blocks the thread until another thread wakes it.
import { Worker, isMainThread, workerData } from 'node:worker_threads';
if (isMainThread) {
const flag = new Int32Array(new SharedArrayBuffer(4));
const worker = new Worker(new URL(import.meta.url), { workerData: flag });
setTimeout(() => {
Atomics.store(flag, 0, 1);
Atomics.notify(flag, 0);
}, 50);
await new Promise((resolve) => worker.once('exit', resolve));
} else {
const flag = workerData;
console.log('worker waiting');
const result = Atomics.wait(flag, 0, 0);
console.log('worker woke:', result);
}worker waiting
worker woke: okAtomics.wait(flag, 0, 0) sleeps only if the value at index 0 is still 0. If it has already changed it returns 'not-equal' at once, which closes the race between checking and sleeping. The main thread stores the new value first and then calls Atomics.notify, and the worker returns 'ok'. The third possible result is 'timed-out' when you pass a timeout.
Never call Atomics.wait on a browser main thread, where it throws. Use Atomics.waitAsync there, as in the browser version.