Sub topic 7
Atomic Load, Store, and Read-Modify-Write Operations
This chapter assumes you know how to create a SharedArrayBuffer, wrap it in a typed array view, and pass it to a worker. It also assumes you have seen why counter[0]++ loses updates when several threads run it at once. The goal here is the working model of the basic Atomics functions: what each one does, what it returns, which views it accepts, and the mistakes people make with it.
What "atomic" means for a single operation
An atomic operation is indivisible. No other thread can see it half-finished, and no other thread's operation on the same element can land in the middle of it. Every Atomics function takes the same first two arguments, a typed array and an element index, and acts on exactly that one element.
The basic functions fall into three groups:
- Load reads one element.
- Store writes one element.
- Read-modify-write (RMW) reads an element, computes a new value, and writes it back as one step. The step returns the value that was there before the change.
Atomics.compareExchange is also an RMW operation. It gets its own chapter because it is the base for conditional updates and locks.
Atomics.load and Atomics.store
Atomics.load(ta, i) returns the current value of ta[i]. Atomics.store(ta, i, v) writes v and returns v.
const sab = new SharedArrayBuffer(16);
const i32 = new Int32Array(sab); // 4 elements
Atomics.store(i32, 0, 10);
console.log(Atomics.load(i32, 0)); // 10You might expect these to behave just like i32[0] and i32[0] = 10. Two things make them different:
- Indivisibility. The element is read or written as a whole, with no tearing.
- Ordering and visibility. Atomic operations are sequentially consistent. The engine cannot reorder them around each other, and it cannot cache the value in a register. A plain read inside a loop such as
while (i32[0] === 0) {}may be hoisted by the JIT compiler and never see another thread's write.while (Atomics.load(i32, 0) === 0) {}always re-reads memory. A later chapter covers the full ordering guarantees.
The return value of store catches people out. It returns the value after integer conversion, not the value that ended up in memory:
const i8 = new Int8Array(new SharedArrayBuffer(1));
console.log(Atomics.store(i8, 0, 300)); // 300
console.log(Atomics.load(i8, 0)); // 44 (300 wrapped to 8 bits)
console.log(Atomics.store(i8, 0, 3.7)); // 3If you need the stored value, read it back with load.
Read-modify-write operations
| Function | New value of `ta[i]` | Returns | Column |
|---|---|---|---|
| `Atomics.add(ta, i, v)` | old + v | old value | |
| `Atomics.sub(ta, i, v)` | old − v | old value | |
| `Atomics.and(ta, i, v)` | old & v | old value | |
| `Atomics.or(ta, i, v)` | old \ | v | old value |
| `Atomics.xor(ta, i, v)` | old ^ v | old value | |
| `Atomics.exchange(ta, i, v)` | v | old value |
const i32 = new Int32Array(new SharedArrayBuffer(16));
Atomics.store(i32, 0, 10);
console.log(Atomics.add(i32, 0, 5)); // 10 (old value)
console.log(Atomics.load(i32, 0)); // 15
console.log(Atomics.sub(i32, 0, 3)); // 15
console.log(Atomics.exchange(i32, 0, 100)); // 12
console.log(Atomics.load(i32, 0)); // 100Each call reads, computes, and writes with no gap that another thread could use. That is why the shared-counter example from earlier in the tutorial always reaches the exact total:
const { Worker, isMainThread, workerData } = require('node:worker_threads');
const WORKERS = 4;
const ITERATIONS = 100000;
if (isMainThread) {
const sab = new SharedArrayBuffer(4);
const counter = new Int32Array(sab);
let finished = 0;
for (let i = 0; i < WORKERS; i++) {
const w = new Worker(__filename, { workerData: sab });
w.on('exit', () => {
if (++finished === WORKERS) {
console.log(Atomics.load(counter, 0)); // 400000
}
});
}
} else {
const counter = new Int32Array(workerData);
for (let i = 0; i < ITERATIONS; i++) {
Atomics.add(counter, 0, 1);
}
}Using the returned old value
Because RMW operations return the previous value, each caller learns something that no other caller learned. Atomics.add therefore works as a ticket dispenser. Every worker that calls it gets a distinct number, even when the calls happen at the same moment:
// Each worker claims a unique slot index in a shared results array.
function claimSlot(nextSlot) {
return Atomics.add(nextSlot, 0, 1); // 0, 1, 2, ... never duplicated
}
const nextSlot = new Int32Array(new SharedArrayBuffer(4));
console.log(claimSlot(nextSlot)); // 0
console.log(claimSlot(nextSlot)); // 1Atomics.exchange does the same job for "take and reset". A consumer can drain an accumulated count with const pending = Atomics.exchange(ta, i, 0). No increment that lands between the read and the reset gets lost, because the read and the reset are one step.
Bit flags with and, or, and xor
The bitwise operations let several threads set or clear individual bits in one word without overwriting each other's bits:
const READY = 0b001;
const ERROR = 0b010;
const DONE = 0b100;
const flags = new Uint32Array(new SharedArrayBuffer(4));
Atomics.or(flags, 0, READY | DONE); // set two bits -> 0b101
Atomics.and(flags, 0, ~DONE); // clear DONE -> 0b001
Atomics.xor(flags, 0, ERROR); // toggle ERROR -> 0b011
console.log(Atomics.load(flags, 0).toString(2)); // "11"Here ~DONE is the negative number -5. It converts to the unsigned mask 0xFFFFFFFB when stored into a Uint32Array, so the and call clears only bit 2.
Which views are allowed
Atomics works only on integer typed arrays:
| View | Allowed | Value type |
|---|---|---|
| `Int8Array`, `Uint8Array`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array` | Yes | Number |
| `BigInt64Array`, `BigUint64Array` | Yes | BigInt |
| `Uint8ClampedArray` | No | — |
| `Float32Array`, `Float64Array` | No | — |
Arithmetic wraps modulo the element size, the same as plain typed-array writes. It does not throw on overflow:
const i8 = new Int8Array(new SharedArrayBuffer(1));
Atomics.store(i8, 0, 127);
console.log(Atomics.add(i8, 0, 1)); // 127
console.log(Atomics.load(i8, 0)); // -128The 64-bit views need BigInt operands:
const big = new BigInt64Array(new SharedArrayBuffer(8));
Atomics.add(big, 0, 1n);
console.log(Atomics.load(big, 0)); // 1n
try {
Atomics.add(big, 0, 1); // Number, not BigInt
} catch (e) {
console.log(e.name); // TypeError
}load, store, and the RMW functions also accept views over an ordinary, non-shared ArrayBuffer. That is legal but rarely useful, since only one thread can reach that memory. Atomics.wait is the exception, because it requires shared memory.
Common errors
Composing atomics and expecting atomicity
Each call is atomic on its own. A sequence of calls is not.
// WRONG: another thread can write between the load and the store.
const v = Atomics.load(counter, 0);
Atomics.store(counter, 0, v + 1);
// RIGHT for unconditional arithmetic:
Atomics.add(counter, 0, 1);When the new value depends on the old one in a way no single RMW function covers (for example, "double it, but cap it at 1000"), you need a compare-and-swap loop. The next chapter builds one.
Mixing plain and atomic access
If one thread writes ta[0] = 5 while another calls Atomics.add(ta, 0, 1), the program still has a data race. The plain write gets no ordering guarantee, and the JIT may reorder or remove it. Every access to a location that another thread can touch concurrently must go through Atomics. Plain access is fine only for data that no thread is writing at that time, for example a buffer filled before workers start, or a region handed off under a lock.
Wrong index or view
The index counts elements of the view, not bytes. An index outside the view's length throws a RangeError; it does not return undefined as ta[99] does. Passing a float view throws a TypeError.
const i32 = new Int32Array(new SharedArrayBuffer(16)); // length 4
try { Atomics.load(i32, 4); } catch (e) { console.log(e.name); } // RangeError
const f64 = new Float64Array(new SharedArrayBuffer(8));
try { Atomics.add(f64, 0, 1); } catch (e) { console.log(e.name); } // TypeErrorMisreading the return value
Atomics.add(ta, i, 1) returns the value before the addition. Code that wants the new value must compute Atomics.add(ta, i, 1) + 1. It must not follow the call with a separate load, because another thread may have changed the element in between.
Wrap shared slots in small named helpers such as `incrementPending(view)` or `takePending(view)`. When every access to a slot goes through one helper, a stray plain `view[3] = 0` stands out in review.Exercise
Four workers each run const id = Atomics.add(next, 0, 1); exactly once on a shared Int32Array that starts at 0. Afterward the main thread reads Atomics.load(next, 0). Which values can the workers' id variables hold, and what does the main thread read?
Show answer
The four ids are 0, 1, 2, and 3, each held by exactly one worker. Which worker gets which id depends on timing. The main thread reads 4. Atomics.add returns the old value and never hands the same old value to two callers.
Exercise
A worker counts processed jobs with Atomics.add(stats, 0, 1). Once a second the main thread reports the count and resets it with const n = Atomics.load(stats, 0); Atomics.store(stats, 0, 0);. Why can increments go missing, and what single call fixes it?
Show answer
An increment that lands after the load and before the store gets overwritten by the store of 0, so it is never reported. Replace both lines with const n = Atomics.exchange(stats, 0, 0);, which reads the count and resets it in one indivisible step.
Exercise
What does this print, and why? const u8 = new Uint8Array(new SharedArrayBuffer(1)); console.log(Atomics.sub(u8, 0, 1), Atomics.load(u8, 0));
Show answer
It prints 0 255. Atomics.sub returns the old value, 0. The subtraction wraps modulo 2^8 in a Uint8Array, so the element becomes 255. Atomics arithmetic never throws on overflow.