Read-Write Locks
Shared access for readers, exclusive access for writers: the three fairness policies and who starves, a tested Python lock, why upgrading deadlocks, and Java's ReentrantReadWriteLock and StampedLock.
Overview
A read-write lock has two modes. Any number of threads can hold the read lock at the same time, because reading does not change the data. The write lock is exclusive: while a thread holds it, nobody else reads or writes. For data that is read far more often than it is written, such as a configuration map or an in-memory directory, readers stop waiting for each other.
It is not a free upgrade from a mutex. It is more complex, so each acquire costs more; it needs a policy for who goes next when readers and writers both wait; and it has a deadlock trap that a plain lock does not (upgrading). Interviewers use it to see whether you know those costs.
Shared and exclusive
The whole mechanism is one compatibility rule: can a new request be granted, given what is held right now?
- Nothing is held: a new read request is granted, and so is a new write request.
- The read lock is held, by one or more threads: a new read request is granted, subject to the policy below. A new write request waits until every reader leaves.
- The write lock is held, by one thread: a new read request waits, and so does a new write request.
Here is the middle case played out with two readers and a writer.
- Reader 1 acquires the read lock. It is granted, and the reader count is 1.
- Reader 2 acquires the read lock. It is granted too, and the count is 2.
- The writer asks for the write lock and waits, because the count is above 0.
- Reader 1 releases its read lock, and the count drops to 1.
- Reader 2 releases its read lock, and the count drops to 0.
- The lock grants the write lock to the writer, which holds it alone.
- The writer releases the write lock.
The two readers overlap; the writer gets the lock only when the last reader leaves.
Interview questions
- What is a read-write lock, and when is it better than a mutex?
- What is the readers-writers problem, and how do the three policies differ?
- Implement a read-through cache with a read-write lock. What is the classic bug?
- What does StampedLock add, and when would you use it?
- When should you not use a read-write lock?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio