How to Implement Read-Write Locks
Use a read-write lock: let many readers in at once, exclude writers from readers, and avoid writer starvation with a fair policy.
On this page
Introduction
A plain mutex serializes every access to the shared state, so even concurrent reads wait their turn. When reads dominate and do not conflict with each other, that serialization wastes the concurrency: ten readers could proceed in parallel but are queued one at a time. A read-write lock lets many readers hold the lock at once while a writer holds it exclusively, matching the actual conflict pattern of the data.
This tutorial implements a read-write lock: concurrent readers, exclusive writers, a fairness policy that prevents writer starvation, and tests for concurrency and exclusion. The examples use an async implementation, and the same semantics appear as RWMutex in Go and ReentrantReadWriteLock in Java.
Let readers proceed together
Readers do not modify the state, so any number of them can hold the lock at once. The lock tracks the count of active readers; a reader acquires if no writer holds or waits, and releases by decrementing the count. When the count returns to zero and a writer is waiting, the writer proceeds. This is the core of the read path and the reason a read-write lock exists.
Reads must genuinely be safe to run together. If a reader can observe a partial state without the write lock coordinating, then the state is not protected by the read lock alone. The lock only helps if the read under the read lock is consistent with the write under the write lock, which requires the write to make its changes atomically with respect to the readers.
class ReadWriteLock {
private readers = 0;
private writer = false;
private waitingWriters = 0;
private queue: (() => void)[] = [];
async read<T>(fn: () => Promise<T>): Promise<T> {
await this.acquireRead();
try { return await fn(); } finally { this.releaseRead(); }
}
async write<T>(fn: () => Promise<T>): Promise<T> {
await this.acquireWrite();
try { return await fn(); } finally { this.releaseWrite(); }
}
private acquireRead(): Promise<void> {
if (!this.writer && this.waitingWriters === 0) { this.readers++; return Promise.resolve(); }
return new Promise((res) => this.queue.push(() => { this.readers++; res(); }));
}
private releaseRead() {
this.readers--;
if (this.readers === 0) this.releaseNext();
}
// writer acquisition and releaseNext omitted for brevity
}
Exclude writers from readers
A writer needs exclusive access, so it waits until the reader count is zero, then it holds the lock alone, blocking new readers while it runs. This is what makes a write atomic with respect to reads: no reader observes the state mid-write. The writer releases by clearing its flag and letting the queued reader or writer proceed.
The exclusivity must cover the write’s whole critical section, including any await inside it. If the write awaits mid-modification, readers blocked behind it wait longer, but the guarantee holds: no reader enters until the write releases. Keep the write’s critical section as short as the atomic change allows, because it is the part that serializes all the reads.
Prevent writer starvation with a fair policy
If new readers can always enter while a writer waits, a steady stream of reads starves the write. The policy that prevents it is to make a waiting writer block new readers: once a writer is queued, a new reader waits behind it rather than jumping in. This is a fairness trade that slightly delays new reads to guarantee the write proceeds.
The opposite policy, reader-preference, favors throughput for readers at the risk of never running a write under continuous read load. Writer-preference, once a writer waits, blocks new readers; it is the safer default when writes must make progress. Some implementations add aging, promoting a long-waiting writer or reader, to guarantee progress in both directions. Choose the policy from whether writes or reads can tolerate delay.
// Go's RWMutex: writers get priority once they are waiting, so reads do not starve a write
var mu sync.RWMutex
var value State
func Read() State {
mu.RLock()
defer mu.RUnlock()
return value // many readers proceed together
}
func Write(next State) {
mu.Lock()
defer mu.Unlock()
value = next // exclusive: no reader observes a partial write
}
Beware of upgrade deadlocks
A common mistake is to hold the read lock and try to acquire the write lock to upgrade, which deadlocks: the write lock cannot be acquired while this same holder (or any reader) holds a read lock. Upgrades are not supported by a basic read-write lock, so if a read may need to become a write, structure the code to release the read lock before acquiring the write lock, accepting the window where the state may have changed.
Alternatively, use a lock that supports an explicit upgrade, or make the operation a write from the start if it almost always ends up writing. The lesson is that read-write locks have two lock modes with a strict ordering, and a lock held in read mode cannot be silently promoted. Design the code around that rather than hitting a deadlock in production.
Test concurrency, exclusion, and starvation
Test that several readers run concurrently, by having each reader hold the lock briefly and asserting the peak concurrent reader count is greater than one. Test that a writer excludes readers, by asserting no reader is active while a writer holds the lock. Test that a writer is not starved by a stream of readers: with writer-preference, a queued writer enters within a bounded number of reader completions.
node -e '
const lock = new ReadWriteLock();
let readers = 0, peak = 0, writerActive = false, violation = false;
const read = () => lock.read(async () => { readers++; peak = Math.max(peak, readers); if (writerActive) violation = true; await sleep(5); readers--; });
Promise.all([...Array(10)].map(read)).then(() => console.log("peak readers:", peak, "violation:", violation));
'
Common pitfalls
Holding a read lock and trying to upgrade to a write lock, which deadlocks, a stream of new readers that starves a waiting writer, a write critical section that awaits for long and blocks all reads, and using a read-write lock where reads are not actually safe to run together are the recurring mistakes. No in-place upgrade, writer-preference or aging, a short write section, and using the lock only when reads are independent address them.
Conclusion
A read-write lock matches the conflict pattern of shared data: many readers together, writers alone. Let readers proceed concurrently, exclude writers from readers with a write critical section that is short, choose a policy that prevents writer starvation, and never try to upgrade a read lock in place. Self-check by asserting concurrent readers, exclusive writers, and a writer that is not starved. Then read-heavy state gets the concurrency a plain mutex would have wasted.
Sources: MDN: Concurrency and shared state, Go: sync.RWMutex, Java: ReentrantReadWriteLock.
FAQ
- When is a read-write lock better than a mutex?
- When reads are frequent and writes are rare, and reads do not conflict. A mutex would serialize every read, throwing away the concurrency. A read-write lock lets the many reads proceed together and only serializes the writes.
- How do I prevent writer starvation?
- Give a waiting writer priority over new readers: once a writer is queued, new readers wait behind it. Without this, a continuous stream of readers keeps the lock held read-side and the writer never gets in. Some locks also add aging to guarantee progress.
Report a problem with this articleOpens a pre-filled issue on GitHub.