How to Choose Between a Mutex and a Semaphore
Pick the right synchronization primitive: mutex for exclusive access, semaphore for bounded concurrency, and keyed locks for partitioned state.
On this page
Introduction
Choosing the wrong synchronization primitive is a common source of either a performance loss or a correctness bug. A mutex protects state that only one operation may touch at a time, so it serializes access; a semaphore allows a bounded number of holders at once, so it limits concurrency to a resource. Using a global mutex where a keyed one fits serializes unrelated work; using a semaphore where a mutex is needed allows two operations to corrupt shared state.
This tutorial lays out the decision: identify the invariant, use a mutex for exclusivity, a semaphore for a bound, and a keyed lock when the state is partitioned. The examples use async primitives, and the reasoning matches the synchronous primitives of any language.
Identify the invariant the primitive must protect
The choice follows from what must be true while an operation runs. If the invariant is that only one operation may read and write the state at a time, you need exclusivity, which is a mutex. If the invariant is that no more than N operations may use a resource at once, you need a bound, which is a semaphore. Read the requirement as a statement about how many may hold at once, and the primitive follows.
A related question is whether the state is partitioned. If different operations touch disjoint parts, a single lock over all of them is coarser than necessary. Keying the lock by the partition lets operations on different parts run in parallel while the same part serializes, which is usually the right shape for per-entity state.
Use a mutex for exclusive access
A mutex allows one holder at a time, so any operation that reads then writes the shared state is not interleaved with another. Wrap the read-modify-write in the mutex, and release it in a finally so a thrown error does not hold the lock forever. Keep the critical section to the state access, not to unrelated awaited work, so the lock is held briefly.
A mutex has ownership: the holder releases it. A bare semaphore with one permit does not track ownership, so a different caller could release it, which is a bug. Use a mutex when exclusivity is the requirement, and rely on its ownership semantics rather than emulating them with a one-permit semaphore.
import { Mutex } from 'async-mutex';
const mutex = new Mutex();
async function updateShared() {
await mutex.runExclusive(async () => { // only one holder at a time
const current = await read();
await write(transform(current));
});
}
Use a semaphore for a bounded resource
A semaphore allows up to a permit count of holders at once, so it caps concurrency to a resource’s capacity. A database pool of ten, an API that accepts five concurrent calls, or a disk with limited parallel IO map to a semaphore whose permit count is that capacity. Unlike a mutex, more than one holder is allowed, which is exactly right when the resource tolerates concurrency but not unbounded concurrency.
The semaphore does not protect a read-modify-write invariant by itself, because two holders can run concurrently. Its purpose is to limit load, not to serialize access. Use it to keep the pressure on a resource within what the resource can take, and use a mutex when access itself must be exclusive.
class Semaphore {
private permits: number; private waiters: (() => void)[] = [];
constructor(n: number) { this.permits = n; }
async run<T>(fn: () => Promise<T>): Promise<T> {
if (this.permits <= 0) await new Promise<void>((r) => this.waiters.push(r));
else this.permits--;
try { return await fn(); }
finally { const w = this.waiters.shift(); if (w) w(); else this.permits++; }
}
}
Key the lock when the state is partitioned
When the state is per-entity, a global lock serializes operations on different entities that do not conflict. A keyed mutex keeps a separate lock per key, so operations on different keys run in parallel and operations on the same key serialize. This limits contention to where the conflict actually is, and it scales with the number of keys rather than capping the whole system at one operation.
Implement the keyed mutex as a map from key to a chain of promises, so each key has its own queue. Clean up the map entry when its chain is empty, or a long-lived key map grows without bound. Key on the entity id, the user id, or whatever partitions the state, and never on a value that changes per request, which would make every key unique and defeat the serialization.
class KeyedMutex {
private chains = new Map<string, Promise<unknown>>();
async run<T>(key: string, fn: () => Promise<T>): Promise<T> {
const prev = this.chains.get(key) ?? Promise.resolve();
const next = prev.then(fn, fn);
this.chains.set(key, next.catch(() => {}));
try { return await next; }
finally { if (this.chains.get(key) === next) this.chains.delete(key); } // no leak
}
}
Recognize the read-heavy case
When reads dominate and writes are rare, a plain mutex serializes the reads, which throws away concurrency. A read-write lock, covered elsewhere, allows concurrent readers and exclusive writers, matching the conflict pattern. It is a specialization of the mutex decision: exclusivity is needed only between a writer and any reader, not between two readers.
A counting semaphore can also express a bound on readers if the concern is the load on the source, but a read-write lock expresses the correctness invariant. Choose by whether the requirement is about load or about consistency. The load variant is a semaphore; the consistency variant for read-write access is an RWMutex.
Test the primitive against its requirement
For a mutex, test that two concurrent read-modify-writes do not interleave, so the final state is correct where the unguarded version would lose an update. For a semaphore, test that the peak concurrency equals the permit count and never exceeds it. For a keyed mutex, test that different keys run in parallel while the same key serializes. Each test should fail on the wrong primitive and pass on the right one.
node -e '
// mutex: two concurrent increments must both apply
const m = new Mutex();
Promise.all([m.runExclusive(() => inc()), m.runExclusive(() => inc())])
.then(() => console.log("mutex result:", value)); // 2, not 1
// semaphore: peak concurrency must equal its permits
'
Common pitfalls
A global mutex where a keyed one fits, serializing unrelated work, a semaphore used to protect a read-modify-write so two holders corrupt the state, a one-permit semaphore emulating a mutex without ownership, releasing a mutex from a different caller than the holder, and a keyed mutex whose map grows without bound are the recurring mistakes. Keyed locks for partitioned state, a mutex for exclusivity, a semaphore for bounds, ownership-correct release, and cleanup of the key map address them.
Conclusion
Choose the primitive from the invariant. A mutex gives exclusive access for read-modify-write; a semaphore bounds concurrency to a resource’s capacity; a keyed mutex serializes only the same key when the state is partitioned; a read-write lock allows concurrent reads. Self-check by asserting a mutex prevents interleaving, a semaphore caps the peak concurrency, and a keyed mutex parallelizes different keys. Then the primitive matches the requirement instead of distorting the system around it.
Sources: MDN: Synchronization primitives in async code, Go: sync.Mutex and sync.RWMutex, Go: golang.org/x/sync/semaphore.
FAQ
- Is a semaphore with one permit a mutex?
- Functionally yes, it allows one holder at a time. In practice a mutex also carries ownership and reentrancy semantics, such as the holder releasing it, that a bare semaphore does not. Use a mutex for exclusive access and a semaphore for a count greater than one.
- When do I need a keyed lock?
- When the shared state is partitioned by an identifier, like a per-user cache or a per-document update. A single global lock serializes unrelated keys and hurts throughput; a keyed lock serializes only the same key, which is the actual conflict.
Report a problem with this articleOpens a pre-filled issue on GitHub.