A read-write lock lets many readers in at once but gives a writer exclusive access. It fits data that is read far more often than it changes: a config, a routing table, an in-memory cache. Reads never conflict with each other, so making them queue behind a plain mutex wastes parallelism. The catch is fairness: if readers may always join the ones already inside, a writer can wait forever, and the fix (let a waiting writer block new readers) makes readers wait longer instead.
Think of it like
A museum room and the restorer
Any number of visitors can look at a painting together; nobody needs the room to themselves to look. The restorer, though, needs the room empty: nobody may watch a half-cleaned canvas. If the guard keeps letting new visitors in while the restorer waits at the door, on a busy day the restorer never gets in (reader preference, and writer starvation). If the guard stops new visitors as soon as the restorer arrives and lets the room empty out, the restorer gets in quickly, but the visitors in the queue now wait for the whole restoration (writer preference).
The problem
A service keeps its database address in memory as two fields, host and port, which always change together. Request threads read them all the time; an admin thread replaces them now and then. Three readers (R1, R2, R3) and one writer (W1) share them in the visualizer above. The safe first version guards both fields with one mutex. This is the Before version.
class ConfigHolder {
private final Lock m = new ReentrantLock();
private String host = "a.db";
private int port = 5432;
Config read() {
m.lock();
try {
return new Config(host, port);
} finally {
m.unlock();
}
}
void write(String h, int p) {
m.lock();
try {
host = h;
port = p;
} finally {
m.unlock();
}
}
}It is correct, and that matters: without any lock, W1 could write host = b.db, then R1 could read host and port before W1 writes the port, and R1 would hold b.db:5432, an address that never existed. That is a torn read: reading one field without a lock can be fine (a volatile reference, an atomic), but two fields that must match cannot be read safely while a writer may be between its two writes. (The tests behind the visualizer include a version with no lock at all, and the exhaustive search finds exactly this torn read.) But the mutex is also wasteful. Two readers never conflict, yet they take turns: with the Readers share schedule, the Before version never has more than one reader inside, and R2 and R3 spend 9 steps blocked behind R1 and each other.
The pattern
Intent: allow any number of threads to read shared data at the same time while a thread that changes it has it to itself. The lock has two modes: a shared one for readers and an exclusive one for writers. The idea goes back to Courtois, Heymans and Parnas, whose 1971 paper Concurrent Control with "Readers" and "Writers" gave two solutions: one that favors readers and one that favors writers.
- Read lock (shared)
- Held by any number of readers at once. Taking it waits only while a writer holds the lock (and, with writer preference, while a writer is waiting).
- Write lock (exclusive)
- Held by one writer, with no readers. Taking it waits until no reader and no other writer holds the lock.
- Reader preference
- New readers may join the readers already inside even while a writer waits. Best throughput for reads; a steady stream of readers can keep a writer out forever.
- Writer preference
- Once a writer is waiting, new readers wait behind it. The writer gets in as soon as the current readers leave; the readers that arrived after it wait for the whole write.
- Fair mode
- Roughly first come, first served: a writer waits for readers that came before it, and readers that come after a waiting writer wait for it. Neither side starves, at some cost in throughput.
- Starvation
- A liveness problem, not a safety one: no invariant breaks, but a thread that wants the lock never (or only very late) gets it.
- Downgrade
- A writer takes the read lock before releasing the write lock, so it can keep reading what it wrote while no other writer slips in. Safe, and supported by Java's
ReentrantReadWriteLock. - Upgrade
- A reader asks for the write lock while still holding its read lock. The write lock waits for every reader to leave, including the one asking, so it deadlocks. Most read-write locks do not allow it.
The visualizer builds the lock from parts you already know from Producer-Consumer: one mutex m that guards the lock's own fields, and two condition variables. readers counts the readers inside, writer says whether a writer is inside, and in the writers-first version waitingWriters counts writers waiting at the door. The mutex is held only for the bookkeeping; the actual reading happens outside it, which is what lets readers overlap. Writers first changes three lines: lockWrite does waitingWriters++ before its loop and waitingWriters-- after it, and lockRead waits while (writer || waitingWriters > 0). Every wait sits in a while loop, as in producer-consumer: a woken thread re-checks, because another thread may have taken the lock between the signal and the wake-up.
void lockRead() {
m.lock();
while (writer) okToRead.await();
readers++;
m.unlock();
}
void unlockRead() {
m.lock();
readers--;
if (readers == 0) okToWrite.signal(); // last reader out
m.unlock();
}
void lockWrite() {
m.lock();
while (writer || readers > 0) okToWrite.await();
writer = true;
m.unlock();
}
void unlockWrite() {
m.lock();
writer = false;
okToWrite.signal(); // maybe another writer
okToRead.signalAll(); // and every waiting reader
m.unlock();
}What the visualizer shows
- Versions: Before (one mutex), Readers first and Writers first (the read-write lock above). The same schedule can be replayed on each.
- Config and lock state:
hostandport(tinted while a writer has changed one but not the other), the lock's fieldsreaders,writerandwaitingWriters, who is inside reading or writing, the most readers ever inside together, what each reader got, and how long W1 has waited and which readers got in ahead of it. - Invariants: A writer is alone (never a writer together with a reader or another writer) and No torn read (every reader gets a
hostandportfrom the same write). They are checked after every step. - Threads over time: one lane per thread. Amber is a step running, sky blue a thread that wants
m(blocked, or woken and waiting to re-acquire it), violet a thread asleep onokToReadorokToWrite. - Stats: most readers at once, reader wait steps (steps the readers spent blocked or asleep, the bands in their lanes) and W1 wait steps.
- Schedules: Readers share, Readers keep coming and Writer first tell the stories below; Seeded random draws an interleaving and Manual lets you pick each step. Each step is one atomic action of one thread on a simulated single processor, so the numbers count steps, not time.
Walkthrough
- 1
Three readers get in (steps 1 to 12)
With Readers first and Readers share selected, R1 locks
m, checkswriter(false), doesreaders++and unlocksm: it holds the read lock. R2 and R3 do the same. From step 11 the panel showsreaders 3and all three inside. - 2
They read together (steps 13 to 21)
R1, R2 and R3 read
hostin turn, thenport: six read steps with all three inside at once. On a multi-core machine these reads would run in parallel; with one mutex they had to take turns. - 3
The writer waits (steps 16 to 18)
In the middle of the reads W1 calls
lockWrite: it locksm, findsreaders > 0and waits onokToWrite, which releasesm. Its lane turns violet. The readers are not disturbed. - 4
The last reader out signals (steps 22 to 30)
Each reader locks
m, decrementsreadersand unlocks. R1 and R2 leave other readers inside, so they do not signal. R3 bringsreadersto 0 at step 29 and signalsokToWrite; W1's lane turns sky blue: woken, but it needsmback first. - 5
The writer is alone (steps 31 to 36)
W1 re-acquires
m, checks again (no reader, no writer), setswriter = trueat step 33 and unlocksm. It writeshostat step 35, when the panel shows the config half-written, andportat 36. Nobody else is inside. - 6
Release (steps 37 to 39)
unlockWritesetswriter = falseand signals both conditions; nobody is waiting, so the signals do nothing. 39 steps, both invariants held, at most three readers inside, and the readers never waited. - 7
Now let readers keep coming
Choose Readers keep coming. W1 asks while R1 is reading and falls asleep at step 8. R2 enters at step 11, R1 leaves, R3 enters at step 19, R2 leaves: there is always a reader inside, and each one is allowed in because only
writeris checked.readersfirst reaches 0 when the last reader leaves at step 29, and W1 gets the write lock at step 33 after 23 wait steps. The panel says it plainly: 2 readers (R2, R3) got in while it waited. - 8
And give writers the priority
Switch to Writers first with the same schedule. W1 announces itself (
waitingWritersbecomes 1) at step 7, so R2 and R3 find a writer waiting and sleep onokToRead. When R1 leaves, W1 gets in at step 22 after 11 wait steps. The price moves to the readers: they waited 31 steps in total (0 with readers first), and they read the new config,b.db:6543.
Before and after
Before: one mutex
- Correct: no torn read, the writer is always alone
- One thread inside at a time, even when all of them only read
- Cheap: lock and unlock, 4 steps per read in the visualizer
- Fine when the critical section is tiny or writes are frequent
Readers first
- Readers share the lock: up to three inside at once here
- Readers never wait for each other, only for a writer
- More bookkeeping: 9 steps per read instead of 4
- A steady stream of readers starves the writer
Writers first
- Readers still share the lock
- A waiting writer stops new readers, so it gets in soon
- Readers that arrive behind a writer wait for the whole write
- A steady stream of writers can starve the readers instead
| Schedule | Before (one mutex) | Readers first | Writers first |
|---|---|---|---|
| Readers share | 19 steps; 1 reader at a time; readers wait 9 steps | 39 steps; 3 readers at once; readers wait 0; W1 waits 13 | 40 steps; 3 readers at once; readers wait 0; W1 waits 13 |
| Readers keep coming | 19 steps; W1 writes at step 8; readers wait 4 | 39 steps; W1 waits 23 and gets in at step 33, after R2 and R3 | 46 steps; W1 waits 11 and gets in at step 22; readers wait 31 |
| Writer first | 19 steps; readers wait 8, one at a time | 45 steps; one signalAll at step 17 wakes R1, R2 and R3, who then read together | 46 steps; the same, at step 18 |
m or asleep on a condition.Two honest observations. First, the read-write lock runs more steps than the mutex: each read pays for locking m twice and updating readers, which is real overhead (a read-write lock is a more complex object than a mutex), and the gain only appears when reads are long enough, and threads are many enough, for overlapping them to pay off. Second, the policy does not change safety: an exhaustive search of every interleaving of the visualizer's program, run in its tests, finds no step where a writer is together with a reader or another writer, no torn read and no deadlock, in all three versions. It changes who waits.
Variations
| Policy | A new reader waits when | Risk | Examples |
|---|---|---|---|
| Reader preference | A writer holds the lock | Writers starve under steady reads | The first Courtois et al. solution; glibc's pthread_rwlock_t by default |
| Writer preference | A writer holds the lock or is waiting | Readers starve under steady writes | Go's sync.RWMutex; the second Courtois et al. solution |
| Fair (arrival order) | A writer that came earlier is still waiting | Lower throughput: readers stop batching up | Java's ReentrantReadWriteLock in fair mode |
std::shared_mutex leaves it unspecified and Rust's RwLock depends on the operating system.Java's default (non-fair) ReentrantReadWriteLock documents no order at all and warns that a continuously contended non-fair lock may postpone a reader or writer indefinitely. Its implementation does make a new reader wait when the first thread in the queue is a writer, a heuristic against writer starvation rather than a guarantee. In fair mode a reader blocks if the write lock is held or a writer is waiting, and when the lock is released it goes either to the longest-waiting writer or to the group of readers that has waited longer than every writer.
Downgrading: write, then keep reading
rw.writeLock().lock();
try {
host = h;
port = p;
rw.readLock().lock(); // allowed: this thread holds the write lock
} finally {
rw.writeLock().unlock(); // now only the read lock is held
}
try {
use(host, port); // no writer can change them meanwhile
} finally {
rw.readLock().unlock();
}Why upgrading deadlocks
rw.readLock().lock();
if (cacheIsStale()) {
rw.writeLock().lock(); // waits until no reader holds the lock...
refresh(); // ...but this thread is a reader
rw.writeLock().unlock();
}
rw.readLock().unlock();Java's documentation allows the downgrade above and says upgrading from a read lock to the write lock is not possible. The write lock waits for readers == 0, and the thread asking is one of those readers, so it waits for itself. With two threads it is worse: each holds a read lock and waits for the other to leave. The visualizer's tests confirm it: a thread that calls lockRead and then lockWrite on the lock above deadlocks on every schedule, alone or in pairs. The fix is to release the read lock, take the write lock, and check again (another thread may have refreshed in between). C#'s ReaderWriterLockSlim offers an upgradeable read mode instead, which only one thread can hold at a time, so two upgraders can never wait for each other; databases use update (U) locks in SQL Server for the same reason.
Optimistic reads: StampedLock
private final StampedLock sl = new StampedLock();
Config read() {
long stamp = sl.tryOptimisticRead(); // no lock taken
String h = host;
int p = port;
if (!sl.validate(stamp)) { // a writer got in meanwhile
stamp = sl.readLock(); // fall back to a real read lock
try {
h = host;
p = port;
} finally {
sl.unlockRead(stamp);
}
}
return new Config(h, p);
}Java 8's StampedLock adds a third mode. An optimistic read takes no lock: it reads a version stamp, copies the fields, and then checks that no writer has taken the lock since. If one has, the copy may be torn, so it is thrown away and the read is retried under a real read lock. Readers then cost almost nothing and never block a writer. The catches: the values read before validate may be inconsistent, so you may only copy them, not act on them; StampedLock is not reentrant and has no conditions. The Linux kernel's seqlock works the same way: the writer bumps a sequence counter before and after writing, and a reader retries if the counter changed or was odd.
No lock for readers: copy-on-write and RCU
- Immutable snapshot: keep the config in one immutable object behind a single reference (
volatilein Java, an atomic in C++). A writer builds a new object and swaps the reference; a reader reads the reference once and uses that object. Readers never wait and can never see a torn value, because nobody changes an object after publishing it. - Copy-on-write collections: Java's
CopyOnWriteArrayListcopies the whole array on every write; iteration needs no lock. Great for listener lists that are read on every event and changed rarely; terrible for anything written often. - RCU (read-copy-update): the Linux kernel's version for linked structures. Readers run without locks; a writer publishes a new version and frees the old one only after every reader that might still see it has finished (a grace period).
- Sharding: split the data and give each part its own lock (Java's
ConcurrentHashMaptakes this further with per-bin locking and lock-free reads), so most threads never contend at all.
In real code
| Where | API | Notes |
|---|---|---|
| Java | ReentrantReadWriteLock | readLock(), writeLock(); non-fair by default, new ReentrantReadWriteLock(true) for fair mode; reentrant; downgrade allowed, upgrade not; only the write lock supports Conditions; at most 65535 holds of each kind |
| Java | StampedLock (Java 8) | Stamps instead of owners: readLock(), writeLock(), tryOptimisticRead() plus validate(), tryConvertToWriteLock(); not reentrant |
| C++ | std::shared_mutex (C++17) | std::shared_lock for readers, std::unique_lock or std::lock_guard for writers; the priority policy is unspecified; no upgrade. C++14 has std::shared_timed_mutex |
| Go | sync.RWMutex | RLock/RUnlock, Lock/Unlock. Documented: once a goroutine is blocked in Lock, new RLock calls block until the writer has had its turn, which is why recursive read locking can deadlock |
| Rust | std::sync::RwLock<T> | read() and write() return guards that unlock when dropped; the policy depends on the operating system; a writer that panics poisons the lock |
| Python | No read-write lock in threading | Build one from threading.Condition (below) or use a package. The GIL does not make a two-field update atomic: a thread can be switched out between the two assignments |
| POSIX / C | pthread_rwlock_t | pthread_rwlock_rdlock, _wrlock, _unlock; glibc prefers readers by default; its non-portable pthread_rwlockattr_setkind_np can select a writers-first kind |
| C# | ReaderWriterLockSlim | EnterReadLock, EnterWriteLock, and EnterUpgradeableReadLock for the one thread allowed to upgrade |
| Databases | Shared (S) and exclusive (X) row locks | The same idea per row, inside transactions; MVCC databases (PostgreSQL, InnoDB) let plain reads skip locks by reading a snapshot |
type Config struct {
mu sync.RWMutex
host string
port int
}
func (c *Config) Get() (string, int) {
c.mu.RLock()
defer c.mu.RUnlock()
return c.host, c.port
}
func (c *Config) Set(host string, port int) {
c.mu.Lock()
defer c.mu.Unlock()
c.host, c.port = host, port
}When to use it, and when not to
Reach for a read-write lock when
- Reads far outnumber writes (configs, caches, routing tables)
- Each read does real work under the lock (walks a structure, formats output)
- Many threads read at the same time on several cores
- The data is too big to copy on every write
Think twice when
- The critical section is a few field reads: a plain mutex is cheaper
- Writes are frequent: readers and writers just take turns, with more overhead
- The data is small: an immutable snapshot behind one reference needs no reader lock
- Readers need to upgrade to writers: restructure first
- You need a fairness guarantee your library does not document
Read-write lock vs similar patterns
| Approach | Readers together? | Writers vs readers | Best for |
|---|---|---|---|
| Mutex | No | Everyone takes turns | Short critical sections, frequent writes |
| Read-write lock | Yes | Writer waits for readers; policy decides who goes first | Long reads, rare writes |
Optimistic read (StampedLock, seqlock) | Yes, without locking | Writer never waits for readers; readers retry | Tiny, hot reads of a few fields |
| Immutable snapshot / copy-on-write | Yes, without locking | Writer copies and swaps; readers keep the old copy | Small data, rare writes |
| RCU | Yes, without locking | Writer publishes a new version, frees the old one later | Kernel-style read-mostly linked structures |
| Producer-Consumer | Not the point | Hands items from one side to the other | Passing work between threads |
Implementation
Three readers and a writer share a host and port that must change together. Java uses ReentrantReadWriteLock and shows a downgrade; C++ uses std::shared_mutex with shared_lock and unique_lock. Python's standard library has no read-write lock, so the Python version builds a small writers-first one on threading.Condition. JavaScript runs on one thread, so the TypeScript version is an async writers-first lock: it matters only when a read or an update spans an await, as in the demo, where the readers that arrive while the writer waits read the new config together.
import threading
from contextlib import contextmanager
class RWLock:
"""Writers-first read-write lock built on one Condition."""
def __init__(self):
self._cond = threading.Condition() # owns a mutex
self._readers = 0
self._writer = False
self._waiting_writers = 0
@contextmanager
def read(self):
with self._cond:
while self._writer or self._waiting_writers > 0:
self._cond.wait()
self._readers += 1
try:
yield # the read itself runs without holding the mutex
finally:
with self._cond:
self._readers -= 1
if self._readers == 0:
self._cond.notify_all()
@contextmanager
def write(self):
with self._cond:
self._waiting_writers += 1
while self._writer or self._readers > 0:
self._cond.wait()
self._waiting_writers -= 1
self._writer = True
try:
yield
finally:
with self._cond:
self._writer = False
self._cond.notify_all() # readers and writers share it
class ConfigCache:
def __init__(self):
self._lock = RWLock()
self._host, self._port = "a.db", 5432
def get(self):
with self._lock.read():
return self._host, self._port
def set(self, host, port):
with self._lock.write():
self._host = host
self._port = port
if __name__ == "__main__":
cache = ConfigCache()
def reader(name):
host, port = cache.get()
print(f"{name} read {host}:{port}") # never a mix of two
def writer():
cache.set("b.db", 6543)
print("W1 wrote b.db:6543")
threads = [threading.Thread(target=reader, args=(f"R{i}",))
for i in range(1, 4)]
threads.append(threading.Thread(target=writer))
for t in threads:
t.start()
for t in threads:
t.join()Key takeaways
- A read-write lock has a shared mode for readers and an exclusive mode for writers: readers overlap, a writer is alone. In the visualizer three readers are inside at once, where one mutex allowed one.
- It can be built from one mutex and two conditions: the mutex guards only the counters (
readers,writer,waitingWriters), and the read itself runs outside it. - The policy decides who waits. Readers first starves a writer under steady reads (W1 waits 23 steps while R2 and R3 go ahead); writers first lets the writer in (11 steps) but readers wait longer (31 steps instead of 0).
- Starvation is a liveness problem: every invariant holds, yet a thread may never get in. Fair mode, writer preference or a bounded wait are the fixes.
- Downgrading (take the read lock, then release the write lock) is safe; upgrading a read lock to a write lock deadlocks. Release, take the write lock, and re-check.
- It is not free: more bookkeeping per read than a mutex. For short critical sections or frequent writes use a mutex; for tiny hot reads consider optimistic reads or an immutable snapshot.
Common pitfalls
- Upgrading in place: calling
writeLock().lock()while holding the read lock blocks forever, because the write lock waits for every reader, including the caller. - Assuming a policy:
std::shared_mutexand Rust'sRwLockpromise none, and Java's non-fair default may postpone a thread indefinitely. If starvation matters, choose a lock that documents its policy. - Recursive read locking with a writers-first lock: in Go, a goroutine that calls
RLocktwice can deadlock if a writer queues in between, since the secondRLockwaits for the writer, which waits for the first. - Using a read-write lock for tiny critical sections or write-heavy data, where its overhead makes it slower than a plain mutex.
- Changing data under the read lock: the read lock does not stop other readers, so any write (even "just" updating a cache entry or a counter) needs the write lock.
Interview tips
- When asked to implement one, start with the state (
readers,writer,waitingWriters), thenlockRead,unlockRead,lockWrite,unlockWritewithwhileloops, and name your policy before the interviewer asks. - Be ready for the classic follow-ups: writer starvation and how
waitingWritersfixes it, why upgrades deadlock, and what a fair mode does. - Show judgment: say when you would not use one (short critical sections, frequent writes) and mention the alternatives:
StampedLockoptimistic reads, an immutable snapshot behind an atomic reference, copy-on-write, or RCU.
Real-world applications
- In-memory configuration, feature flags and routing tables: read on every request, replaced rarely.
- Caches and lookup tables shared by request threads, such as a DNS cache or a schema registry.
- File systems and kernels: Linux uses read-write semaphores (
mmap_lockguards a process's memory map) and seqlocks for timekeeping. - Databases: shared and exclusive row and table locks are the same idea, per row and per transaction.
- Game and simulation state read by many systems each frame and updated by one.
Test yourself
With Readers first and the Readers keep coming schedule, why does W1 wait 23 steps although each reader only reads for a few steps?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.