Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท child_process, worker_threads and cluster

JavaScript Atomics in Node.js

Reference for the Atomics object in Node.js: indivisible reads and writes on shared memory, add, compareExchange, wait, notify, waitAsync and building a simple lock.

Atomics is a built-in JavaScript object with static methods that read and modify integer typed arrays in a way that cannot be interrupted by another thread. It exists for SharedArrayBuffer: when several worker threads see the same memory, an ordinary array[0]++ can lose updates, while Atomics.add(array, 0, 1) always counts correctly.

Besides indivisible arithmetic, Atomics provides wait() and notify(), which let a thread sleep until another thread signals a change. With them you can build locks, semaphores and queues between threads. All methods take a typed array, an index, and usually a value.

NODE
const shared = new SharedArrayBuffer(16);
const cells = new Int32Array(shared);

Atomics.add(cells, 0, 5);          // cells[0] is now 5, returns the old value 0
console.log(Atomics.load(cells, 0));

Try it

Node.js The read-modify-write operations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js wait() and notify() between threads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
Atomics.add(typedArray, index, value)             // also sub, and, or, xor
Atomics.load(typedArray, index)
Atomics.store(typedArray, index, value)
Atomics.exchange(typedArray, index, value)
Atomics.compareExchange(typedArray, index, expected, replacement)
Atomics.wait(int32Array, index, expected[, timeoutMs])   // "ok" | "not-equal" | "timed-out"
Atomics.waitAsync(int32Array, index, expected[, timeoutMs])   // { async, value }
Atomics.notify(int32Array, index[, count])               // number of threads woken
Atomics.isLockFree(byteSize)
Name Description
typedArray An Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array or BigUint64Array. Float32Array, Float64Array and Uint8ClampedArray are not allowed. For wait/notify it must be an Int32Array or BigInt64Array.
index The element to operate on. Out of range throws RangeError.
value, expected, replacement Numbers (or BigInt for the 64-bit arrays), converted to the element type.
timeoutMs How long wait() may sleep. Default Infinity.
count Maximum number of waiters to wake. Default Infinity.

Returns: add, sub, and, or, xor, exchange and compareExchange return the value that was in the cell before the operation; load returns the current value; store returns the value you passed. wait() returns 'ok', 'not-equal' or 'timed-out'. notify() returns the number of woken threads. waitAsync() returns { async: false, value: 'not-equal' | 'timed-out' } or { async: true, value: Promise } that resolves to 'ok' or 'timed-out'.

Errors: TypeError for an unsupported array type; RangeError for a bad index.

Usage notes

  • Atomic does not mean ordered across several cells. Each call is indivisible and also sequentially consistent, but a sequence of calls is not one transaction. Protect multi-step updates with a lock.
  • Compare-and-swap loops are the building block for lock-free code: read the old value, compute a new one, compareExchange(array, i, old, new), and retry if the returned value differs from old.
  • A simple mutex is a cell with values 0 (free) and 1 (held): acquire with while (Atomics.compareExchange(a, 0, 0, 1) !== 0) Atomics.wait(a, 0, 1); and release with Atomics.store(a, 0, 0); Atomics.notify(a, 0, 1);.
  • wait() blocks the thread. Use it in workers. In the main thread it freezes timers and I/O; use Atomics.waitAsync() there, which returns a promise instead of blocking.
  • wait() needs a SharedArrayBuffer. On a normal ArrayBuffer it throws TypeError. notify() on a non-shared buffer simply returns 0.
  • Always re-check the condition after wait() returns, because of timeouts and spurious wake-ups between several waiters.
  • Plain reads are allowed but racy. cells[1] can read a stale or half-updated value if another thread is writing without synchronization; publish data with Atomics.store() of a flag after writing it.
  • Values wrap. Atomics.add() on an Int8Array wraps around at 127, as with typed array assignment.