Building a Simple Mutex
You'll learn how to combine Atomics operations to implement a mutual exclusion lock that protects critical sections from concurrent access.
What Is a Mutex?
A mutex (mutual exclusion lock) ensures only one thread can execute a critical section at a time. Think of it like a bathroom key in a coffee shop: only the person holding the key can enter, and everyone else must wait until the key is returned.
Building One with Atomics
We can combine Atomics.compareExchange (to try acquiring the lock) and Atomics.wait/Atomics.notify (to block and wake threads) to create a basic mutex:
class Mutex {
constructor() {
this.sharedBuffer = new SharedArrayBuffer(4);
this.lockState = new Int32Array(this.sharedBuffer);
// lockState[0]: 0 = unlocked, 1 = locked
}
lock() {
while (true) {
// Try to acquire: if currently 0, set to 1
const oldValue = Atomics.compareExchange(this.lockState, 0, 0, 1);
if (oldValue === 0) {
// Successfully acquired!
return;
}
// Lock is held by another thread, wait until notified
Atomics.wait(this.lockState, 0, 1);
}
}
unlock() {
// Release the lock
Atomics.store(this.lockState, 0, 0);
// Wake one waiting thread
Atomics.notify(this.lockState, 0, 1);
}
}
How It Works
lock()spins tryingcompareExchangeuntil it successfully changes the state from 0 to 1- If the lock is already held, the thread blocks with
Atomics.wait unlock()resets the state to 0 and wakes one waiting thread withAtomics.notify
Now you can wrap critical sections:
mutex.lock();
// Critical section: only one worker at a time
sharedData[0] += 1;
mutex.unlock();
Key Takeaway: A mutex built with Atomics.compareExchange, wait, and notify prevents race conditions by ensuring only one thread executes protected code at a time.