Read-write lock
medium 50 minMany readers or one writer, never both.
Video lesson · Chapter 1 of 6
Make a prediction
Read-write lock
1:04Reel
Theory
Read or listen first. About 2 min.
What it is
A read-write lock is a lock with two modes. In shared mode any number of threads may hold it, to read. In exclusive mode exactly one thread holds it, to write, and nobody reads meanwhile.
It keeps the promise of an ordinary lock, that nobody sees a half-finished change, and adds one freedom: readers do not wait for readers.
Two decisions are hidden in each implementation. Who goes next when both kinds wait, and whether a thread may change its mode or enter twice.
Why it exists
Much data is read far more often than changed: prices, settings, routes, permissions. Two reads can not disturb each other, so making them wait is waste.
The gain is real when reading takes a while and several cores read at once. Then eight cores do up to eight times as much.
It is also a way to say something in code. A method that takes the read lock promises not to change anything, and a reviewer can check that.
The costs are real as well: bookkeeping per read, a writer that may starve, and two traps that a plain lock does not have.
A short history
1971
Courtois, Heymans and Parnas publish Concurrent control with readers and writers in October. It states the problem with two versions: no reader waits for a waiting writer, and no writer waits longer than necessary.
2004
Java 5 adds
ReentrantReadWriteLockinjava.util.concurrent.locks, with an optional fair mode and downgrading.2010
Brandenburg and Anderson's article on spin-based reader-writer synchronization for real-time systems appears online. It covers phase-fair locks, where readers and writers take turns in phases.
2014
Java 8 adds
StampedLockwith optimistic reading.2017
C++17 adds
std::shared_mutex.
Words to know
- Shared mode
- The read lock. Many holders.
- Exclusive mode
- The write lock. One holder, alone.
- Torn read
- A mixture of old and new values that never existed together.
- Starvation
- A thread that could go on is passed over again and again.
- Barging
- A newcomer enters before those who wait.
- Upgrade
- From read to write without releasing. Two at once is a deadlock.
- Downgrade
- From write to read without a gap. Safe.
- Reentrant
- The thread that holds the lock may take it again.
- Optimistic read
- Read without a lock, then check whether a writer came in between.
- Snapshot
- A version of the data that never changes, reached by one reference.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Share. Readers enter together and are counted.
Understand it
Story
The hall with one mosaic
Looking at something does not change it. So ten people may look at the same time. Changing it is different: while it is being changed, a person who looks sees something that never existed.
The board counts readers. The rope is the policy. The closed door is the write lock.
Four participants
ReadWriteLock
Counts readers, knows whether a writer is inside, and decides who is next. ReentrantReadWriteLock, RWMutex, shared_mutex.
Read lock (shared)
Many may hold it. It blocks writers, not other readers.
Write lock (exclusive)
One may hold it. It blocks readers and other writers.
Readers and writers
Threads that promise to take the right lock and to release it. The lock can not check what they do inside.
Who may join whom
| Holding | A reader asks | A writer asks |
|---|---|---|
| Nobody | enters | enters |
| Readers | enters (if no writer is waiting) | waits |
| A writer | waits | waits |
The problem
What goes wrong without it
A shop has a price list. Forty tills ask it all day, and a manager changes it a few times. A change often touches two prices that belong together: the tea becomes dearer, the cake cheaper, the set stays at 700.
prices = {"tea": 300, "cake": 400}def total(): return prices["tea"] + prices["cake"]def change(between): prices["tea"] = 320 between() # a till asks at this moment prices["cake"] = 380seen = []print(total()) # 700change(lambda: seen.append(total()))print(seen) # [720], a price that never existedprint(total()) # 700assert seen == [720]This is a torn read: half old, half new. An ordinary lock repairs it. It also makes forty tills stand in one line for something that none of them changes. If reading takes long, that line is the shop's speed limit.
The design that hurts
1/3The lock lies beside the data
Nothing forces anyone to take it. A new report class reads the prices without it, and no test notices.
usesdepends on
The idea
A lock with two doors
The lock offers two handles to the same state. Both look like ordinary locks, so code can be handed the one it needs and nothing more.
Read-write lock in general
1/5Two small interfaces
ReadWriteLock hands out two locks. Lock is what everybody knows: lock, unlock, try.
implementsowns (dies together)
shared_mutex.Readers, then a writer, then readers
The lock as a state diagram
Five scenes to know
| Scene | Call | Result |
|---|---|---|
| Several readers | read lock, read lock | Both at once |
| A writer waits | write lock while readers are in | Sleeps until the last one leaves |
| A writer is in | read lock or write lock | Sleeps |
| A reader behind a waiting writer | read lock | Depends on the policy |
| Try | tryLock while a writer is in | False at once, the thread does something else |
The promise
Policy
Who goes next?
The rule many or one says nothing about the line outside. With a writer waiting and a new reader arriving, somebody must decide. Any choice hurts somebody.
Readers are inside, a writer waits, a new reader arrives.
BreaksReaders first
- How
- The new reader enters.
- Limit
- If reads overlap without a gap, the counter never reaches 0 and the writer waits for ever.
- Choose when
- Writers that may wait any time, or readers that come in clear waves.
WorksWriters first
- How
- New readers wait while any writer waits.
- Limit
- A steady stream of writers starves readers. A thread that reads twice, nested, can block itself.
- Choose when
- Rare writes that should be seen soon. This is what we build.
StrongFirst come, first served, readers in groups
- How
- One line. Neighbouring readers enter together.
- Limit
- A little slower: groups are smaller. Nested reads are still dangerous.
- Choose when
- When neither side may starve. See the FAANG page Policies.
from collections import dequedef play(arrivals, policy, read=2, write=2, limit=60): """Time steps instead of threads. arrivals: {time: 'R' or 'W'}. Returns who entered when.""" wait, inside, entered, t, n = deque(), [], [], 0, {"R": 0, "W": 0} while t < limit and (arrivals.keys() - range(t) or wait or inside): inside = [(k, end) for k, end in inside if end > t] for kind in arrivals.get(t, ""): n[kind] += 1 wait.append((kind, f"{kind}{n[kind]}")) while True: writing = any(k == "W" for k, _ in inside) if writing or not wait: break can = [w for w in wait if w[0] == "R" or not inside] if policy == "readers first": can.sort(key=lambda w: w[0]) # R before W elif policy == "writers first": can = [w for w in can if w[0] == "W" or all(x[0] == "R" for x in wait)] else: # fair: only the head of the line can = [w for w in can if w is wait[0]] if not can: break kind, name = can[0] wait.remove(can[0]) inside.append((kind, t + (read if kind == "R" else write))) entered.append((name, t)) t += 1 return enteredstream = {0: "R", 1: "RW", 2: "R", 3: "R", 4: "R", 5: "R", 6: "R", 7: "R"}for policy in ("readers first", "writers first", "fair"): out = play(stream, policy) print(f"{policy:14}", "W1 enters at", dict(out)["W1"], "| last reader at", max(t for n, t in out if n[0] == "R"))Readers first let the writer in at step 9, when the stream had ended. With a stream that never ends the answer is never. The other two policies let it in at 2 and 3.
What your library does
| Library | Policy | Again by the same thread? |
|---|---|---|
Java ReentrantReadWriteLock | Unspecified order by default, about first come with true | Yes. Write then read works, read then write waits for ever |
Go sync.RWMutex | A blocked writer excludes new readers | No. Not for reading either |
Rust std::sync::RwLock | Depends on the system, no promise | May deadlock or panic |
C++ std::shared_mutex | Left to the implementation | Undefined behavior |
| POSIX on glibc | Prefers readers by default, can be set | Reads may be nested in that default |
Judgement
When to use it and when not
A read-write lock is more expensive than a plain lock. Each reader must change the counter when it enters and leaves. It pays only if reading itself takes clearly longer than that, and if reads really overlap.
Fits
- Many more reads than writes
- Reads that take a while: search, copy, sum
- Several processor cores that really read at once
- Data that must change in place
- Caches, routing tables, configuration, permissions
Does not fit
- Many writes: it becomes a slow plain lock
- Reads of a few nanoseconds: the counter is the bottleneck
- A single value: use an atomic reference
- One thread, or no overlap
- Reading that secretly writes, such as a cache that counts hits
Which protection?
The price
Cost per read
Two changes of one shared counter, seen by all cores.
Starvation
Somebody may wait very long, depending on the policy.
New traps
Upgrade and nested reads. A plain lock does not have them.
A promise by hand
Nothing stops a change under the read lock. Return copies, not the inner map.
Summary
The whole topic in one minute.
Many readers or one writer, never both. Three numbers are enough: readers, writer, waiting writers. Readers wait for the last two, writers for the first two.
Readers first starves writers, writers first starves readers, one line or phases starve nobody. A waiting writer that gives up must wake the others.
Never upgrade: release, take write, check again. Measure before replacing a plain lock, and think of a snapshot when readers may finish with the version they began with.
- Many readers or one writer, never both.
- The lock protects a moment: all values that belong together change under one write lock.
- The policy decides who starves. Know the one of your library.
- Write to read is possible (downgrade). Read to write is a trap (upgrade).
- Measure. For short reads a plain lock wins, for old copies a snapshot wins.