Skip to content
jshacks.dev
Async

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.

1 min read
Summarize in AI

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.

signal.mjsJavaScript
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);
}
Text
worker waiting
worker woke: ok

Atomics.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.

Taggednode 24
Share

More snippets

Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.