Sub topic 11
Building a Mutex from Atomics
This chapter assumes you have read the earlier chapters on Atomics.compareExchange and on Atomics.wait and Atomics.notify. It also assumes you can run a Node.js script that uses worker_threads. The goal is to combine those two building blocks into a mutex, a lock that lets only one thread at a time enter a section of code. You will start with a short version, find where it falls short, and then improve it.
Why Atomics Alone Are Not Enough
Every single Atomics operation is indivisible. Many real updates, however, touch more than one memory slot. Suppose a shared buffer holds two account balances, and a transfer subtracts from one and adds to the other. A thread between the two steps can see money missing. Making each step atomic does not fix this, because the gap between the steps is the problem.
A mutex closes that gap. While one thread holds the lock, every other thread that wants it must wait. The code between lock() and unlock() is called the critical section. Other threads see it as if it happened all at once.
The Two-State Mutex
The simplest design uses a single Int32Array slot with two values:
| Value | Meaning |
|---|---|
| 0 | Unlocked |
| 1 | Locked |
const UNLOCKED = 0;
const LOCKED = 1;
function lock(i32, index) {
while (Atomics.compareExchange(i32, index, UNLOCKED, LOCKED) !== UNLOCKED) {
Atomics.wait(i32, index, LOCKED);
}
}
function unlock(i32, index) {
Atomics.store(i32, index, UNLOCKED);
Atomics.notify(i32, index, 1);
}Each line has a specific job:
compareExchangetries to change 0 to 1. It returns the old value. If the old value was 0, this thread won the lock and the loop ends.- If the old value was 1, another thread holds the lock.
Atomics.wait(i32, index, LOCKED)puts the thread to sleep, but only if the slot still holds 1. If the holder unlocked between the failed CAS and the wait,waitreturns'not-equal'at once and the loop tries again. Becausewaitchecks the value and sleeps in one step, a wake-up cannot be lost in that gap. unlocksets the slot back to 0 and wakes at most one sleeping thread. That thread goes around the loop and retries the CAS.
The loop also covers the case where a woken thread loses the race. Thread C may grab the lock before woken thread B gets to it. B's CAS then fails, and B goes back to sleep. Nothing breaks. The cost is that the lock is not fair: no thread is guaranteed a turn in arrival order.
A Runnable Example: Protecting an Invariant
This Node.js script runs four workers. Each one moves one unit between two balances 50,000 times. Two workers move from A to B and two move from B to A. Inside the critical section, each worker checks that the total is still 2000.
const { Worker, isMainThread, workerData } = require('node:worker_threads');
const LOCK = 0, A = 1, B = 2;
const WORKERS = 4;
const ITERATIONS = 50000;
function lock(i32, index) {
while (Atomics.compareExchange(i32, index, 0, 1) !== 0) {
Atomics.wait(i32, index, 1);
}
}
function unlock(i32, index) {
Atomics.store(i32, index, 0);
Atomics.notify(i32, index, 1);
}
if (isMainThread) {
const sab = new SharedArrayBuffer(3 * Int32Array.BYTES_PER_ELEMENT);
const i32 = new Int32Array(sab);
i32[A] = 1000;
i32[B] = 1000;
let finished = 0;
let violations = 0;
for (let id = 0; id < WORKERS; id++) {
const w = new Worker(__filename, { workerData: { sab, id } });
w.on('message', (n) => { violations += n; });
w.on('exit', () => {
if (++finished === WORKERS) {
console.log({ a: i32[A], b: i32[B], violations });
// { a: 1000, b: 1000, violations: 0 }
}
});
}
} else {
const { sab, id } = workerData;
const i32 = new Int32Array(sab);
const [from, to] = id % 2 === 0 ? [A, B] : [B, A];
let violations = 0;
for (let i = 0; i < ITERATIONS; i++) {
lock(i32, LOCK);
if (i32[A] + i32[B] !== 2000) violations++;
i32[from] -= 1;
i32[to] += 1;
unlock(i32, LOCK);
}
process.parentPort?.postMessage?.(violations);
require('node:worker_threads').parentPort.postMessage(violations);
}Delete the lock and unlock calls and run it again. The final balances drift, and violations is usually far above zero.
The critical section uses plain reads and writes such as i32[from] -= 1. That is safe because the atomic operations on the lock slot order memory. Everything written before unlock's Atomics.store is visible to the next thread once its compareExchange succeeds. The chapter on memory ordering explains this happens-before rule. For now, the rule to follow is: touch the protected data only while holding the lock.
The Cost of Always Notifying
The two-state unlock calls Atomics.notify every time, even when no thread is waiting. In most engines, notify takes an internal lock on the engine's wait queue. When the mutex is uncontended, that work is wasted on every release.
The fix is to record whether anyone might be waiting. This is the classic futex mutex described by Ulrich Drepper in "Futexes Are Tricky". It uses three states:
| Value | Meaning |
|---|---|
| 0 | Unlocked |
| 1 | Locked, no waiters |
| 2 | Locked, waiters may exist |
function lock(i32, index) {
let c = Atomics.compareExchange(i32, index, 0, 1);
if (c === 0) return; // fast path: no contention
if (c !== 2) c = Atomics.exchange(i32, index, 2);
while (c !== 0) {
Atomics.wait(i32, index, 2);
c = Atomics.exchange(i32, index, 2);
}
}
function unlock(i32, index) {
if (Atomics.sub(i32, index, 1) !== 1) { // old value was 2
Atomics.store(i32, index, 0);
Atomics.notify(i32, index, 1);
}
}Two details matter here:
- A waiter that wakes up and takes the lock sets the slot to 2, not 1. It cannot know whether other threads are still asleep, so it assumes they are. This sometimes causes one extra
notify, but a wake-up is never missed. unlockusesAtomics.subto move 1 to 0 in a single step. If the old value was 2, the slot is now 1, andunlockstores 0 and notifies.
| Property | Two-state | Three-state |
|---|---|---|
| Uncontended `lock` | One CAS | One CAS |
| Uncontended `unlock` | Store plus `notify` | One `sub` |
| Correctness under contention | Correct | Correct |
| Code complexity | Low | Moderate |
Use the three-state version when the lock is taken often and usually uncontended. Use the two-state version when clarity matters more.
Using the Lock Safely
If the critical section throws an exception, the lock is never released, and every other thread sleeps forever. Wrap the section in a helper:
function withLock(i32, index, fn) {
lock(i32, index);
try {
return fn();
} finally {
unlock(i32, index);
}
}Other traps to watch for:
- Not reentrant. A thread that calls
locktwice without unlocking deadlocks on itself. The slot does not record who owns it. - No owner check. Any thread can call
unlock, even one that never locked. To catch that bug, store a thread ID in a second slot and check it inunlock. - Typed array type.
Atomics.waitworks only on anInt32Arrayor aBigInt64Arraybacked by aSharedArrayBuffer. AUint32Arraythrows aTypeError. - Lock ordering. If two threads take two mutexes in opposite orders, they can deadlock. Always take multiple locks in one fixed order.
Locking from the Main Thread
In browsers, Atomics.wait throws a TypeError on the main thread. In Node.js it is allowed there, but it freezes the event loop while it waits. For threads that must stay responsive, build the waiting step on Atomics.waitAsync:
async function lockAsync(i32, index) {
while (Atomics.compareExchange(i32, index, 0, 1) !== 0) {
const result = Atomics.waitAsync(i32, index, 1);
if (result.async) await result.value;
}
}This works with the two-state unlock shown earlier, because Atomics.notify wakes async waiters as well as blocking ones. Keep the critical section short and synchronous. If you await while holding the lock, every worker that wants the lock stays blocked until the main thread's task finishes.
Exercise
In the two-state lock, why is it safe for a thread to call Atomics.wait(i32, index, 1) even though the lock might have been released just after its compareExchange failed?
Show answer
Atomics.wait compares the slot with the expected value and goes to sleep as one atomic step. If the holder already stored 0, the comparison fails, wait returns 'not-equal' right away, and the loop retries the CAS. No wake-up can fall into the gap between the check and the sleep.
Exercise
In the three-state mutex, a waiter that wakes up and takes the lock sets the slot to 2 instead of 1. What would go wrong if it set the slot to 1?
Show answer
Other threads might still be asleep in Atomics.wait. With the slot at 1, the next unlock would see Atomics.sub return 1, skip notify, and leave those threads asleep while the lock is free. They could sleep forever. Setting 2 makes sure the next unlock wakes one of them.
Exercise
A worker calls withLock(i32, 0, () => withLock(i32, 0, work)). What happens, and why?
Show answer
The worker deadlocks. The outer call sets the slot to locked. The inner lock fails its CAS and sleeps waiting for the slot to change, but the only thread that could unlock it is the sleeping worker itself. The mutex is not reentrant because it does not track which thread owns it.