Sub topic 11
Building a Mutex from Atomics
This chapter assumes you know Atomics.compareExchange, Atomics.wait, and Atomics.notify from the previous chapters. You should also be able to start Node.js worker threads.
A mutex (mutual exclusion lock) makes sure only one thread at a time runs a section of code. That section is called the critical section. Single atomic operations protect one integer. A mutex protects any group of reads and writes, such as updating two fields that must stay consistent.
The Lock Word
The mutex is a single Int32Array slot in shared memory. It holds one of two values:
| Value | Meaning |
|---|---|
| 0 (`UNLOCKED`) | No thread holds the lock |
| 1 (`LOCKED`) | A thread is inside the critical section |
To take the lock, a thread uses compareExchange to change the slot from 0 to 1. If the call returns 0, the swap worked and the thread owns the lock. If it returns 1, another thread owns it, so the caller sleeps with Atomics.wait until the value changes.
A Working Example
Four workers each update two counters, a and b, with plain non-atomic writes inside the lock. If the lock works, both counters end at the same exact total.
const { Worker, isMainThread, workerData } = require('node:worker_threads');
const UNLOCKED = 0;
const LOCKED = 1;
const LOCK = 0, A = 1, B = 2;
const WORKERS = 4;
const ITERATIONS = 50000;
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);
}
if (isMainThread) {
const sab = new SharedArrayBuffer(3 * Int32Array.BYTES_PER_ELEMENT);
const mem = 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(mem[A], mem[B]); // 200000 200000
}
});
}
} else {
const mem = new Int32Array(workerData);
for (let i = 0; i < ITERATIONS; i++) {
lock(mem, LOCK);
try {
mem[A] = mem[A] + 1; // plain access is safe inside the lock
mem[B] = mem[B] + 1;
} finally {
unlock(mem, LOCK);
}
}
}The plain writes are safe here because the atomic operations on the lock word order them. The thread that next acquires the lock sees every write made before the previous unlock. The chapter on memory ordering explains this guarantee.
Atomics.wait is given LOCKED as its expected value. If the lock is released between the failed compareExchange and the wait call, wait returns 'not-equal' at once and the loop retries. Without that check, a wakeup could be lost.
Common Errors
- Calling
lockon the browser main thread.Atomics.waitthrows there. Use this mutex only in workers, or build an async version onAtomics.waitAsync. - Skipping
try/finally. If the critical section throws, the lock stays held and every other thread sleeps forever. - Locking twice from the same thread. This mutex does not track an owner and cannot be re-entered. A second
lockcall from the holder deadlocks. - Unlocking a lock you do not hold. Nothing prevents this, and it lets two threads into the critical section.
- Forgetting
notify. Waiting threads never wake up.
Exercise
Why does the lock loop pass LOCKED as the expected value to Atomics.wait instead of just calling Atomics.wait(i32, index)?
Show answer
Atomics.wait sleeps only if the slot still holds the expected value. Passing LOCKED means that if the holder unlocks between the failed compareExchange and the wait, the call returns 'not-equal' at once and the loop retries. The thread therefore cannot sleep through a wakeup it has already missed. The two-argument form uses undefined as the expected value, which converts to 0, so the thread would never sleep on a held lock and would spin instead.
Exercise
A worker calls lock(mem, 0), then calls a helper that also calls lock(mem, 0). What happens, and why?
Show answer
The worker deadlocks. The slot already holds LOCKED, so compareExchange fails and the worker waits for an unlock that only it could perform. This mutex cannot be re-entered because it does not record which thread owns it.