Reader Writer Locks
Motivation
- locks provide exclusive access to a piece of shared data
- gets rid of data races, makes reasoning about the shared data easier
- should we always protect accesses to shared data with a lock?
- what if all accesses are reads?
- what if some accesses are reads and some are writes?
- do all writes need to be protected?
- do all reads need to be protected?
Reader Writer Locks
- a type of lock that allows for concurrent read accesses and exclusive write access
- concurrent reads: mutual exclusion on reads is not too restrictive!
- multiple readers can hold the read lock at the same time
- while there are ongoing reads no writes are allowed (avoid reading partial writes!)
- exclusive write: mutual exclusion is necessary for atomic writes
- only one writer can acquire the write lock at a time
- when there is an ongoing write, no reads or other writes are allowed
- APIs
- reader lock:
read_acquire
, read_release
- writer lock:
write_acquire
, write_release
- when can a
read_acquire
succeed?
- should we always let new readers join in?
- when can a
write_acquire
succeed?
- read-preferring vs write-preferring
- given ongoing reads, when a writer comes in, should we keep accepting new readers or do we let the writer acquire the lock after current reads are done?
- given both waiting readers and writers, when a write lock is released, who should we wake up?
- how might we implement a write-preferring reader writer lock with a monitor?
- what conditions do we need?
- how many condition variables do we need?