← Back to Node.js, page 2

nodejs-0037 · Hard senior

How can worker threads share memory safely with SharedArrayBuffer and Atomics?

A SharedArrayBuffer is a block of memory that several threads can read and write. Plain operations such as counter++ are not atomic, so updates can be lost. Atomics.add, compareExchange, wait and notify perform the operation as one indivisible step.

Full answer

Normally worker threads share nothing and copy messages. A SharedArrayBuffer (SAB) changes that. The same bytes appear in every thread that receives the buffer, and you view them through a typed array such as Int32Array.

The danger is the race condition. counter[0]++ is three steps: read, add, write. If two threads read the same old value, both write the same new value, and one increment disappears.

Atomics is the standard object for safe access:

  • Atomics.add, sub, and, or, xor: do the read-modify-write as one step, and return the old value.
  • Atomics.load and store: read and write with ordering guarantees.
  • Atomics.compareExchange(array, index, expected, new): the base of locks and lock-free algorithms.
  • Atomics.wait(array, index, value) and Atomics.notify(array, index, count): block a worker thread until another thread signals. Atomics.wait is not allowed on the main thread in browsers, and should not block the Node main thread either. Atomics.waitAsync is the non-blocking version.

A mutex built on compareExchange is possible, but prefer simpler designs: have one thread own the data and others send messages, or give each worker its own slice of the array and combine the results at the end.

Use SAB for large numeric data (images, matrices, counters, ring buffers). For ordinary objects, messages are simpler and safer.

javascript
const { Worker, isMainThread, workerData } = require('node:worker_threads');

const WORKERS = 4;
const ROUNDS = 100000;

if (isMainThread) {
  const shared = new SharedArrayBuffer(8); // two 32-bit numbers
  const counters = new Int32Array(shared);  // [0] = atomic counter, [1] = plain counter

  let finished = 0;
  for (let i = 0; i < WORKERS; i++) {
    const worker = new Worker(__filename, { workerData: shared });
    worker.once('exit', () => {
      if (++finished < WORKERS) return;
      const expected = WORKERS * ROUNDS;
      console.log('expected total:', expected);
      console.log('Atomics.add total:', Atomics.load(counters, 0), '| correct:', Atomics.load(counters, 0) === expected);
      console.log('plain ++ total never exceeds expected:', counters[1] <= expected);
    });
  }
} else {
  const counters = new Int32Array(workerData);
  for (let i = 0; i < ROUNDS; i++) {
    Atomics.add(counters, 0, 1); // safe
    counters[1]++;                // unsafe: updates can be lost
  }
}

The plain counter usually ends below the expected total, but the exact number changes between runs, so the snippet prints only the facts that are always true. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): expected total: 400000 Atomics.add total: 400000 | correct: true plain ++ total never exceeds expected: true

Key points

  • SharedArrayBuffer is memory visible to all threads.
  • counter++ is not atomic and loses updates.
  • Atomics gives indivisible operations plus wait and notify.
  • Message passing is simpler when sharing is not needed.

Common mistakes

  • Using counter++ on shared memory from several threads.
  • Calling Atomics.wait on the main thread.
  • Sharing memory when messages would do.
  • Assuming a normal object or Map can live in a SharedArrayBuffer.

Follow-ups

  • How would you build a simple lock with compareExchange?
  • What is false sharing and why does it slow threads?
  • How is the data in a SAB laid out for strings or objects?

Tips

  • Start with the lost update picture: read, add, write.
  • Prefer message passing in your answer and treat SAB as the exception.
  • Mention wait and notify for the producer and consumer case.