A read-write lock is a synchronization primitive that allows any number of concurrent readers or exactly one writer to hold it at a time, never both. In concurrency and programming generally, it is also called a readers–writer lock or RW lock, and it exists to exploit a simple observation: operations that only read shared data cannot corrupt it, so they do not need to exclude one another.
Compared with a plain mutex, a read-write lock can raise throughput substantially for read-mostly workloads, such as configuration tables, caches and routing maps. The benefit is not free: the lock is more complex, its bookkeeping costs more per acquisition, and a poorly chosen fairness policy can starve writers or readers.
How a read-write lock coordinates readers and writers
A read-write lock tracks two kinds of ownership: a shared mode for readers and an exclusive mode for writers. Internally, most implementations keep a reader count, a writer flag and one or more wait queues, often packed into a single machine word that is updated with atomic compare-and-swap operations.
When a thread requests read access, the lock admits it immediately if no writer holds the lock and, depending on policy, no writer is waiting. A writer must wait until the reader count drops to zero and no other writer is active. Releasing the last read hold or the write hold wakes the next eligible waiters.
The following table summarizes which requests can be granted in each lock state.
| Current state | New read request | New write request |
|---|---|---|
| Unlocked | Granted | Granted |
| Held by readers | Granted, unless policy blocks it | Waits until all readers leave |
| Held by a writer | Waits | Waits |
| Readers active, writer queued | Depends on fairness policy | Waits |
Because readers proceed in parallel, the lock behaves like a shared critical section for reads and an ordinary critical section for writes. The writer’s exclusivity also provides the memory visibility guarantee: changes made under the write lock are visible to every reader that acquires the lock afterward, since acquire and release imply the necessary memory barriers.
Fairness policies and their trade-offs
The central design decision in any read-write lock is who goes first when both sides are waiting. A steady stream of overlapping readers can keep the reader count above zero indefinitely, so a naive design may never let a writer in. Implementations therefore choose an explicit preference policy.
| Policy | Behavior | Main risk | Typical fit |
|---|---|---|---|
| Reader preference | New readers join while any reader holds the lock | Writer starvation | Rare writes, latency-tolerant updates |
| Writer preference | A waiting writer blocks newly arriving readers | Reader starvation under frequent writes | Updates that must land promptly |
| Phase-fair or FIFO | Readers and writers alternate in arrival order | Lower peak read throughput | Mixed workloads needing bounded waits |
| Unspecified | Left to the platform scheduler | Unpredictable latency | Portable code that tolerates variation |
The POSIX pthread_rwlock_t leaves the default preference largely implementation-defined, and some platforms expose extensions to select writer preference. Java’s ReentrantReadWriteLock offers a fair mode that approximates arrival order, while its default non-fair mode favors throughput. Writer starvation is the most common production symptom of choosing reader preference without measuring write frequency, and it is a form of resource starvation rather than deadlock.
Read-write lock versus related primitives
A read-write lock is one point in a spectrum of tools for protecting shared state, and it is not automatically faster than a mutex. The comparison below places it among its neighbors in the concurrency toolbox.
| Primitive | Concurrent readers | Per-operation cost | Best suited for |
|---|---|---|---|
| Mutex | No | Low | Short critical sections, balanced reads and writes |
| Read-write lock | Yes | Moderate | Long reads, rare writes, many reader threads |
| Spinlock | No | Very low when uncontended | Very short sections, kernel or real-time code |
| Sequence lock | Yes, with retry | Very low for readers | Small data with infrequent writes |
| Read-copy-update | Yes, wait-free reads | Higher write cost | Kernel structures with very rare updates |
The deciding factor is cache-line contention. Every reader that acquires a conventional read-write lock still writes to the shared reader counter, so on many-core machines the counter’s cache line bounces between cores. For very short read sections, this traffic can make a read-write lock slower than a simple mutex. Scalable variants use per-CPU or striped counters to reduce that cost, at the price of more expensive write acquisition.
Upgrading, downgrading and reentrancy
Lock upgrading, converting a read hold into a write hold without releasing it, is the most dangerous operation associated with read-write locks. If two readers both attempt to upgrade, each waits for the other to release its read hold, producing an immediate upgrade deadlock. Most libraries therefore forbid direct upgrades or provide a special upgradable mode that only one thread may hold.
Lock downgrading, from write to read, is safe and commonly supported: the writer acquires the read lock before releasing the write lock, so no other writer can slip in between. Reentrancy rules also differ by platform. Recursive read acquisition can deadlock under writer preference, because a queued writer blocks the second read request while waiting for the first.
- Release the read lock, acquire the write lock, then revalidate the data if an upgrade is needed.
- Use a dedicated upgradable lock mode when the library offers one.
- Avoid recursive read locking unless the documentation explicitly guarantees it.
Choosing and using a read-write lock in practice
A read-write lock pays off when reads dominate, read sections are long enough to amortize the extra bookkeeping, and several threads genuinely read at the same moment. Without all three conditions, a mutex is usually simpler and at least as fast. The decision table below captures the typical reasoning.
| Situation | Recommended choice | Reason |
|---|---|---|
| Reads above about 90 percent, long read sections | Read-write lock | Parallel readers outweigh counter overhead |
| Reads and writes roughly balanced | Mutex | Shared mode rarely helps and costs more |
| Tiny read sections on many cores | Sequence lock or striped lock | Avoids counter cache-line contention |
| Writes must never wait long | Writer-preference or fair lock | Prevents writer starvation |
| Data replaced wholesale on update | Atomic pointer swap | Readers need no lock at all |
Thresholds such as the 90 percent figure are rough guides; the real break-even point depends on core count, section length and hardware. Benchmark with production-like contention before committing, and keep write sections as short as possible, because every writer blocks all readers.
Common mistakes and failure modes
Most read-write lock defects come from mutating data under a read lock or from misjudging the workload. A read lock grants permission to read, not to modify; lazy initialization or cache updates performed under a read hold create a race condition that the lock cannot detect.
| Symptom | Likely cause | Fix |
|---|---|---|
| Updates delayed for seconds | Writer starvation under reader preference | Switch to a fair or writer-preference policy |
| Threads hang on upgrade | Two readers upgrading at once | Release and reacquire, or use an upgradable mode |
| No speedup over a mutex | Short read sections, counter contention | Use a mutex or a scalable lock |
| Corrupted shared state | Writes under a read lock | Take the write lock for every mutation |
The idea in brief
Think of a museum exhibit behind a glass door. Any number of visitors can stand inside and look at the paintings together, because looking does not change anything. When a restorer needs to work on a painting, however, the room must be empty, and nobody else may enter until the work is finished.
A read-write lock applies that rule to data inside a program. Many readers may share access, but a writer needs the room alone. The main challenge is fairness: if visitors keep arriving, the restorer could wait forever, so the lock needs a rule about whose turn comes next.
A practical scenario
A backend team runs a pricing service on a 32-core server. Each request looks up product prices in an in-memory table of about 200,000 entries, and a background job refreshes a few hundred prices every five minutes. Originally the table was protected by a single mutex, and under peak load of roughly 40,000 requests per second, threads spent much of their time waiting for one another.
The team replaced the mutex with a writer-preference read-write lock, so lookups proceed in parallel and the refresh job is never starved. Profiling showed lock wait time falling sharply and tail latency dropping noticeably during peaks. Later, because each refresh rebuilt the whole table anyway, the team switched to building a new table and publishing it with an atomic pointer swap, which removed locking from the read path entirely.