Skip to content
jshacks.dev
Async

Share work between workers with SharedArrayBuffer

Share work between workers with SharedArrayBuffer and Atomics.add in Node.js 24, and see why a plain counter increment loses updates.

1 min read
Summarize in AI

Worker threads normally copy the data you send them. A SharedArrayBuffer is the exception: every thread sees the same memory, so they can update one counter without messages.

counter.mjsJavaScript
import { Worker, isMainThread, workerData } from 'node:worker_threads';

if (isMainThread) {
  const shared = new SharedArrayBuffer(4);
  const counter = new Int32Array(shared);
  const workers = Array.from(
    { length: 4 },
    () => new Worker(new URL(import.meta.url), { workerData: shared }),
  );
  await Promise.all(workers.map((w) => new Promise((resolve) => w.once('exit', resolve))));
  console.log(Atomics.load(counter, 0));
} else {
  const counter = new Int32Array(workerData);
  for (let i = 0; i < 1000; i++) Atomics.add(counter, 0, 1);
}
Text
4000

Four workers each add one thousand times. Atomics.add is a single indivisible read-modify-write, so no increment is lost. Replace it with counter[0]++ and the total usually comes out below 4000, because two threads read the same value before either writes it back. The functions are documented on MDN.

In browsers a SharedArrayBuffer is only available on pages that are cross-origin isolated. In Node.js there is no such rule.

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.