Read-write lock

Also known as: readers–writer lock · RW lock

On this page 8

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 stateNew read requestNew write request
UnlockedGrantedGranted
Held by readersGranted, unless policy blocks itWaits until all readers leave
Held by a writerWaitsWaits
Readers active, writer queuedDepends on fairness policyWaits
Compatibility of lock requests by current state

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.

PolicyBehaviorMain riskTypical fit
Reader preferenceNew readers join while any reader holds the lockWriter starvationRare writes, latency-tolerant updates
Writer preferenceA waiting writer blocks newly arriving readersReader starvation under frequent writesUpdates that must land promptly
Phase-fair or FIFOReaders and writers alternate in arrival orderLower peak read throughputMixed workloads needing bounded waits
UnspecifiedLeft to the platform schedulerUnpredictable latencyPortable code that tolerates variation
Common read-write lock fairness policies

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.

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.

PrimitiveConcurrent readersPer-operation costBest suited for
MutexNoLowShort critical sections, balanced reads and writes
Read-write lockYesModerateLong reads, rare writes, many reader threads
SpinlockNoVery low when uncontendedVery short sections, kernel or real-time code
Sequence lockYes, with retryVery low for readersSmall data with infrequent writes
Read-copy-updateYes, wait-free readsHigher write costKernel structures with very rare updates
How the read-write lock compares with neighboring primitives

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.

SituationRecommended choiceReason
Reads above about 90 percent, long read sectionsRead-write lockParallel readers outweigh counter overhead
Reads and writes roughly balancedMutexShared mode rarely helps and costs more
Tiny read sections on many coresSequence lock or striped lockAvoids counter cache-line contention
Writes must never wait longWriter-preference or fair lockPrevents writer starvation
Data replaced wholesale on updateAtomic pointer swapReaders need no lock at all
Decision guide for selecting a locking strategy

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.

SymptomLikely causeFix
Updates delayed for secondsWriter starvation under reader preferenceSwitch to a fair or writer-preference policy
Threads hang on upgradeTwo readers upgrading at onceRelease and reacquire, or use an upgradable mode
No speedup over a mutexShort read sections, counter contentionUse a mutex or a scalable lock
Corrupted shared stateWrites under a read lockTake the write lock for every mutation
Symptoms, causes and fixes

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.