Course contentsShow
← JavaScript
Lesson 2185 of 2,72345. Workers and ConcurrencyFree lesson

Atomics.add, sub, and, or, xor

Perform atomic arithmetic and bitwise operations that combine read-modify-write into a single step.

Atomics.add, sub, and, or, xor

You'll learn how to perform atomic arithmetic and bitwise operations that safely combine read-modify-write into a single, indivisible step on shared memory.

The Problem with Manual Read-Modify-Write

When multiple workers access shared memory, operations like "read value, add 5, write back" create race conditions. Between reading and writing, another worker might change the value, causing lost updates. You've seen Atomics.load and Atomics.store, but using them separately still leaves a dangerous gap.

Atomic Operations to the Rescue

These methods combine read-modify-write into one atomic step that no other thread can interrupt:

  • Atomics.add(buffer, index, value) — Atomically adds value to the element, returns old value
  • Atomics.sub(buffer, index, value) — Atomically subtracts value, returns old value
  • Atomics.and(buffer, index, value) — Bitwise AND, returns old value
  • Atomics.or(buffer, index, value) — Bitwise OR, returns old value
  • Atomics.xor(buffer, index, value) — Bitwise XOR, returns old value

All operate on Int32Array or Uint32Array views of a SharedArrayBuffer.

How It Works

const sab = new SharedArrayBuffer(4);
const view = new Int32Array(sab);
view[0] = 100;

// Thread-safe increment by 5
const oldValue = Atomics.add(view, 0, 5);
// oldValue = 100, view[0] is now 105

// Even if 10 workers do this simultaneously, no updates are lost
Atomics.add(view, 0, 1); // Safe counter increment

Think of it like a bank transaction: the read-modify-write happens in one locked operation, guaranteeing no interference.

Key Takeaway: Use Atomics.add, sub, and, or, and xor to perform thread-safe arithmetic and bitwise operations on shared memory, eliminating race conditions inherent in separate read-modify-write sequences.