Read-write lock
medium 50 minMany readers or one writer, never both.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Threads around one lock: who is inside, who sleeps, and which policy let them.
Operations
Many or one
Three readers share. A writer waits, writes alone, and the readers come back together.
Step 1 of 8
Free
No reader, no writer.
Step 1: Free
def acquire_read(self): with self._cond: wait until not writer and waiting == 0 self._readers += 1def release_read(self): with self._cond: self._readers -= 1 if self._readers == 0: notify_all()def acquire_write(self): with self._cond: self._waiting_writers += 1 wait until not writer and readers == 0 self._waiting_writers -= 1 self._writer = True- Watch
- The number of readers
- Result
- Hand-over at zero
Only the last reader wakes anybody.
In the real world
The same read-write lock doing real jobs. Pick one and step through it.
Readers without a lock: one reference, frozen tables.
Step 1 of 4
Everybody on table 1
The till loads the reference once.
Step 1: Everybody on table 1
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Upgrading
criticalTwo threads wait for each other. In Java one thread is enough.
Wrongwith lock.reading(): if missing: with lock.writing(): add()Rightwith lock.reading(): found = not missingif not found: with lock.writing(): if missing: add()Locking each value
criticalA change fits between two reads that belong together.
Wronga = prices.get("tea") # locksb = prices.get("cake") # locks againRighttotal = prices.total(["tea", "cake"]) # one lockReturning the inner map
criticalThe caller reads it later, without any lock.
Wrongwith self._lock.reading(): return self._pricesRightwith self._lock.reading(): return dict(self._prices)Release without finally
criticalAfter one exception the counter never reaches 0 again.
Wronglock.acquire_read()x = compute()lock.release_read()Rightwith lock.reading(): x = compute()Slow work inside
majorOne reader in a network call holds up a writer, and the writer holds up all readers.
Wrongwith lock.reading(): send(http, data)Rightwith lock.reading(): copy = dict(data)send(http, copy)A get that writes
majorTwo readers change the list at the same time.
Wrongwith lock.reading(): order.move_to_end(key)Rightwith lock.writing(): order.move_to_end(key)
Interview tips
Ask first
- What must agree?
- How long is a read?
- May it be a little old?
Name the policy
- Who waits behind whom?
- Who can starve?
- What does my library do?
Hide the lock
- Inside the class.
- Guards only.
- Copies out.
Avoid the traps
- No upgrade.
- No nested read.
- No foreign code inside.
Measure
- Plain lock first.
- Snapshot for short reads.
- Longest wait of a writer.