Sub topic 7
Atomic Load, Store, and Read-Modify-Write Operations
This chapter assumes you know typed arrays such as Int32Array, how to share a SharedArrayBuffer between threads, and why plain counter[0]++ loses updates when two threads run it at once. In this chapter you replace those plain accesses with operations from the Atomics object.
What "atomic" buys you
An atomic operation is indivisible. No other thread can see it half done or slip a write into the middle of it. Atomics provides three groups of operations:
| Operation | What it does | Returns |
|---|---|---|
| `Atomics.load(ta, i)` | Reads the element | The current value |
| `Atomics.store(ta, i, v)` | Writes the element | The value written |
| `Atomics.add` / `sub` | Adds or subtracts `v` | The old value |
| `Atomics.and` / `or` / `xor` | Applies a bitwise operation with `v` | The old value |
| `Atomics.exchange(ta, i, v)` | Replaces the element with `v` | The old value |
The last three rows are read-modify-write operations. Each one reads the element, computes a new value and writes it back as a single step. That one step is what fixes the lost-update race.
Seeing the return values
const i32 = new Int32Array(new SharedArrayBuffer(16));
Atomics.store(i32, 0, 10);
console.log(Atomics.load(i32, 0)); // 10
console.log(Atomics.add(i32, 0, 5)); // 10 (old); slot 0 is now 15
console.log(Atomics.sub(i32, 0, 3)); // 15 (old); slot 0 is now 12
console.log(Atomics.or(i32, 1, 0b0101)); // 0 (old); slot 1 is now 5
console.log(Atomics.and(i32, 1, 0b0100)); // 5 (old); slot 1 is now 4
console.log(Atomics.xor(i32, 1, 0b0110)); // 4 (old); slot 1 is now 2
console.log(Atomics.exchange(i32, 2, 99)); // 0 (old); slot 2 is now 99
console.log(Array.from(i32)); // [12, 2, 99, 0]The old value is useful in its own right. Because each Atomics.add returns a value that no other thread received, it works as a ticket dispenser:
// Any thread can call this; every caller gets a unique id.
function nextId(i32) {
return Atomics.add(i32, 0, 1);
}Common errors
- Wrong array type.
Atomicsworks only on integer typed arrays:Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,BigInt64ArrayandBigUint64Array.Float64ArrayandUint8ClampedArraythrow aTypeError. The BigInt arrays need BigInt arguments, for exampleAtomics.add(big, 0, 1n). - Mixing atomic and plain access. One plain
i32[0] = xon a slot that other threads update atomically brings the race back. Every thread should useAtomicsfor every access to a shared slot. - Load-then-store as an "update".
Atomics.store(i32, 0, Atomics.load(i32, 0) + 1)is two atomic steps with a gap between them, so it still loses updates. UseAtomics.add. For updates thatAtomicshas no single operation for, use the compare-and-swap loop covered in the next chapter. - Ignoring overflow. The value wraps at the type's width.
Atomics.addon anInt32Arrayslot holding2147483647stores-2147483648. - Index out of range. This throws a
RangeError. It does not returnundefinedthe way a plain out-of-range read does.
All of these operations are sequentially consistent, which also affects which other writes a thread can see. A later chapter on memory ordering explains what that guarantees.
Exercise
A slot in an Int32Array holds 6. One thread runs Atomics.xor(i32, 0, 3) and then Atomics.exchange(i32, 0, 1). What does each call return, and what is the slot's final value?
Show answer
6 is 0b110 and 3 is 0b011, so the XOR result is 0b101, which is 5. Atomics.xor returns the old value 6 and leaves 5 in the slot. Atomics.exchange returns 5 and leaves 1, so the final value is 1.
Exercise
Why does Atomics.store(i32, 0, Atomics.load(i32, 0) + 1) still lose increments when four workers run it in a loop?
Show answer
The load and the store are separate atomic operations. Another worker can write between them, and the store then overwrites that write with a value computed from a stale read. Atomics.add(i32, 0, 1) does the read and the write as one indivisible step.