Readers share, writers do not
A read write lock separates two access modes. Many threads can hold the read lock at once because reads do not conflict. Only one thread can hold the write lock, and while it does no readers are allowed.
Tracking the state
- A reader count records how many readers currently hold the lock.
- A writer flag records whether a writer is active.
- A new reader may enter only if no writer holds or is granted the lock.
- A writer may enter only when the reader count is zero and no other writer is active.
The fairness problem
If readers keep arriving, a writer can wait forever, called writer starvation. Fair implementations block new readers once a writer is waiting, so the writer eventually proceeds. This trades a little read throughput for progress guarantees.
Key idea
A read write lock admits concurrent readers but an exclusive writer by tracking a reader count and a writer flag; fair variants block incoming readers when a writer waits to prevent writer starvation.