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.
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.
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);
}4000Four 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.