Skip to content
jshacks.dev
Async

How to Use Atomics for a Lock Between Workers in Node.js

Use Atomics for a lock between workers in Node.js: a three-state mutex over SharedArrayBuffer, a safe counter and a check that shows no updates are lost.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka and Redis logos.

Worker threads in Node.js can share memory, and shared memory brings the old problem of two threads changing the same value at once. Two workers that each read a counter, add one and write it back can lose an update, exactly as in any language with threads. A lock fixes it: only the thread that holds the lock may touch the data. JavaScript has no Mutex class, but the Atomics object gives you the pieces to build one on a SharedArrayBuffer. This post builds a three-state lock, shows the lost-update bug it prevents with a test you can reason about, and explains the details that make the lock correct: compare-and-swap, sleeping instead of spinning and waking exactly one waiter. It assumes the background in using Atomics.wait and Atomics.notify and running work in a worker thread, and uses Node.js 24.

The bug: a lost update

A counter in shared memory, incremented by several workers without a lock, loses increments. The read, the add and the write are three separate steps, and another thread can run between them.

unsafe-worker.jsJavaScript
import { workerData, parentPort } from "node:worker_threads";

const counter = new Int32Array(workerData.shared);

for (let i = 0; i < workerData.times; i++) {
  const value = counter[0]; // read
  counter[0] = value + 1;   // write: another thread may have written in between
}

parentPort.postMessage("done");
unsafe-main.jsJavaScript
import { Worker } from "node:worker_threads";

const shared = new SharedArrayBuffer(4);
const counter = new Int32Array(shared);

const workers = [1, 2, 3, 4].map(
  () => new Worker(new URL("./unsafe-worker.js", import.meta.url), { workerData: { shared, times: 100_000 } })
);
await Promise.all(workers.map((w) => new Promise((resolve) => w.once("message", resolve))));

console.log(counter[0] === 400_000 ? "no updates lost" : "updates were lost");
Text
updates were lost

Four workers each added 100,000, so the correct total is 400,000. The program almost always ends below that, because two workers read the same value and both write the same result. The exact total differs on every run, which is why the message does not print it. (The check cannot prove the loss on every run, but on multi-core machines the loss is routine.)

The lock: three states

A lock stored in one Int32 has three values. 0 means unlocked. 1 means locked and nobody is waiting. 2 means locked and at least one thread is waiting. The third state matters for performance: unlock only needs to wake someone when the state is 2, so an uncontended unlock skips the system call.

lock.jsJavaScript
const UNLOCKED = 0;
const LOCKED = 1;
const CONTENDED = 2;

export class Lock {
  constructor(shared, index = 0) {
    this.cells = new Int32Array(shared);
    this.index = index;
  }

  lock() {
    // Fast path: take the lock if it is free.
    let state = Atomics.compareExchange(this.cells, this.index, UNLOCKED, LOCKED);
    if (state === UNLOCKED) return;

    // Slow path: mark the lock contended and sleep until it is released.
    do {
      if (state === CONTENDED || Atomics.compareExchange(this.cells, this.index, LOCKED, CONTENDED) !== UNLOCKED) {
        Atomics.wait(this.cells, this.index, CONTENDED);
      }
      state = Atomics.compareExchange(this.cells, this.index, UNLOCKED, CONTENDED);
    } while (state !== UNLOCKED);
  }

  unlock() {
    const previous = Atomics.exchange(this.cells, this.index, UNLOCKED);
    if (previous === CONTENDED) Atomics.notify(this.cells, this.index, 1);
  }
}

compareExchange(array, index, expected, replacement) writes replacement only if the current value equals expected, and returns the value that was there. That single atomic step lets exactly one thread win the race for the free lock. The loser records that the lock is contended and sleeps with Atomics.wait, which returns at once if the value is no longer 2, so a release between the check and the sleep is not missed. A waiter that wakes takes the lock by moving it to state 2, not 1, because other waiters may still be asleep, and the next unlock must wake one of them.

Treat this as an educational version of a well-known design, the three-state futex mutex. In production, prefer a tested library over a hand-rolled lock, since subtle ordering mistakes produce failures that appear once in millions of runs.

The fixed worker

Wrap the read-modify-write in the lock.

safe-worker.jsJavaScript
import { workerData, parentPort } from "node:worker_threads";
import { Lock } from "./lock.js";

const counter = new Int32Array(workerData.shared, 4); // cell 0 of the data area
const lock = new Lock(workerData.shared, 0);

for (let i = 0; i < workerData.times; i++) {
  lock.lock();
  try {
    counter[0] = counter[0] + 1;
  } finally {
    lock.unlock();
  }
}

parentPort.postMessage("done");
safe-main.jsJavaScript
import { Worker } from "node:worker_threads";

const shared = new SharedArrayBuffer(8); // 4 bytes for the lock, 4 for the counter
const counter = new Int32Array(shared, 4);

const workers = [1, 2, 3, 4].map(
  () => new Worker(new URL("./safe-worker.js", import.meta.url), { workerData: { shared, times: 25_000 } })
);
await Promise.all(workers.map((w) => new Promise((resolve) => w.once("message", resolve))));

console.log(counter[0]);
Text
100000

Four workers added 25,000 each, and the total is exactly 100,000 on every run. The lock sits in the first four bytes of the buffer and the counter in the next four, so the two do not share a cell. The try and finally guarantee release even if the guarded code throws.

Use Atomics.add when a lock is overkill

For a plain counter, a lock is more machinery than needed. Atomics.add performs the read, add and write as one atomic operation.

atomic-add.jsJavaScript
const counter = new Int32Array(new SharedArrayBuffer(4));

for (let i = 0; i < 5; i++) Atomics.add(counter, 0, 2);

console.log(Atomics.load(counter, 0));
Text
10

Prefer a single atomic operation whenever the whole update fits in one: add, sub, and, or, xor, exchange and compareExchange cover many cases. A lock is for protecting a larger critical section, such as updating several fields together, writing a record into a shared buffer or checking and then changing a structure.

What the lock does not give you

The lock protects against concurrent access to the shared memory only if every thread uses it. One worker that skips the lock breaks the guarantee for all. The lock is not re-entrant: a thread that holds it and calls lock() again waits for itself forever. It blocks the calling thread through Atomics.wait, which is allowed in workers but not on a browser's main thread. And it does not detect a thread that crashes while holding it, since the state stays at 1 or 2 and the others wait indefinitely. For critical sections that can fail, keep them short, put the unlock in finally and consider a timeout on Atomics.wait as a way to detect a stuck lock.

When not to share memory

Shared memory is the hardest way to coordinate threads. If workers can communicate by messages, with one owner of the data and others sending requests to it, there is nothing to lock, and bugs of this kind cannot occur. Reach for a shared lock when the data is large enough that copying it is too expensive, or when the update rate is so high that message passing becomes the bottleneck, and measure before you decide that is the case.

Walking through a contended acquire

It helps to trace what happens when two workers, A and B, race for the lock. A calls compareExchange(0 to 1), wins and enters its critical section. B calls the same operation and gets back 1, so it knows the lock is taken. B then tries compareExchange(1 to 2), which succeeds and marks the lock contended, and sleeps in Atomics.wait on the value 2. When A finishes, exchange sets the state to 0 and returns the previous value, 2, so A knows a waiter exists and calls notify to wake one. B wakes, tries compareExchange(0 to 2) and takes the lock, leaving the state at 2 in case a third worker is also waiting. When B unlocks, it sees 2, calls notify and finds nobody to wake, which costs a system call but is harmless, and the state returns to 0.

Notice that nothing here depends on timing. If A unlocks between B's failed attempt and B's sleep, Atomics.wait sees that the value is no longer 2 and returns immediately, and B retries. That property, a sleep that checks its condition atomically, is what makes the design free of lost wake-ups. It is the same idea as the expected-value argument described in the earlier post on wait and notify.

Measuring what a lock costs

A lock is cheap when nobody contends for it and expensive when many threads fight over it. Each contended acquire involves a system call to sleep and another to wake, and threads that wake up often find the lock taken again. Keep the critical section short, do the expensive work outside it and copy what you need into local variables before taking the lock. If profiling shows that threads spend most of their time waiting, the fix is rarely a faster lock. Restructure so that each worker accumulates into its own private counter and the results are combined at the end, which removes the sharing and with it the need for the lock.

Checklist before shipping shared-memory code

Confirm that every access to the protected data goes through the lock, including reads that need a consistent view. Confirm that every lock() has an unlock() in a finally. Confirm that no code path takes two locks in different orders. Confirm that nothing inside a critical section can block on something that another lock holder controls. And run the stress test, many workers and many iterations, on a machine with several cores, since a single-core test hides most races.

Taggedbeginner
Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

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