Sub topic 8
Compare-and-Swap with Atomics.compareExchange
This chapter assumes you know how to share an Int32Array over a SharedArrayBuffer between worker threads, and that you have used Atomics.load, Atomics.store, and Atomics.add. Those built-in read-modify-write operations cover addition, subtraction, and bitwise logic. Some updates need other logic, such as "keep the maximum" or "increment only while below a limit." For those cases you write a compare-and-swap (CAS) loop.
What compareExchange does
Atomics.compareExchange(typedArray, index, expected, replacement) performs one indivisible step:
- It reads the current value at
index. - If that value equals
expected, it writesreplacement. - In both cases it returns the value it read.
You know the swap succeeded when the return value equals expected. If the return value is different, another thread changed the slot after you last read it, and nothing was written.
| Return value | Meaning | What to do |
|---|---|---|
| Equals `expected` | Your write happened | Stop |
| Anything else | Another thread got there first | Retry with the returned value |
The CAS loop
The pattern is to read, compute a new value, attempt the swap, and retry if the swap fails.
The following Node.js program uses a CAS loop to keep the maximum value ever seen across four worker threads:
const { Worker, isMainThread, workerData } = require('node:worker_threads');
const WORKERS = 4;
const PER_WORKER = 100000;
function atomicMax(i32, index, value) {
let current = Atomics.load(i32, index);
while (value > current) {
const previous = Atomics.compareExchange(i32, index, current, value);
if (previous === current) return value; // our write won
current = previous; // someone else wrote; re-check
}
return current;
}
if (isMainThread) {
const sab = new SharedArrayBuffer(4);
const max = new Int32Array(sab);
Atomics.store(max, 0, -2147483648); // smallest Int32
let finished = 0;
for (let id = 0; id < WORKERS; id++) {
const w = new Worker(__filename, { workerData: { sab, id } });
w.on('exit', () => {
if (++finished === WORKERS) {
console.log(Atomics.load(max, 0)); // 399999
}
});
}
} else {
const max = new Int32Array(workerData.sab);
for (let i = 0; i < PER_WORKER; i++) {
atomicMax(max, 0, i * WORKERS + workerData.id);
}
}The loop condition value > current matters. If another thread has already stored a larger value, the loop exits without writing anything. A plain if (value > max[0]) max[0] = value has a gap between the check and the write, so a smaller value can overwrite a larger one.
Common errors
- Not reusing the returned value. After a failed swap,
compareExchangehas already given you the fresh value. CallingAtomics.loadagain works, but it costs an extra read and leaves another window for the value to change. - Checking the wrong thing for success. A successful call returns the old value, not
true. Compare the result toexpected. - Type coercion surprises. Both
expectedandreplacementare converted to the array's element type before the comparison. On aUint8Array, anexpectedof256becomes0. - Using CAS where a built-in exists. A CAS loop for a plain increment is slower than
Atomics.add, because it can retry many times under contention. - The ABA problem. CAS only checks that the value is equal now. If the value changed from A to B and back to A, the swap still succeeds. Counters and maximums don't care about this. Pointer-like indexes into shared structures can, so pair the index with a version number when that matters.
Exercise
Write incrementBelow(i32, index, limit), which atomically adds 1 to the slot only if the current value is less than limit and returns true if it incremented.
Show answer
function incrementBelow(i32, index, limit) { let current = Atomics.load(i32, index); while (current < limit) { const previous = Atomics.compareExchange(i32, index, current, current + 1); if (previous === current) return true; current = previous; } return false; }
Exercise
Thread A reads 5 and calls compareExchange(arr, 0, 5, 9). Just before that call, thread B stored 7. What does A's call return, and what is in the slot afterward?
Show answer
It returns 7. The slot still holds 7, because 7 does not equal the expected 5, so no write happened.