Read Write Locks
A read write lock lets a program distinguish readers from writers so that read heavy data does not serialize unnecessarily. A plain mutex forces every access to take turns, even when most operations only read. A read write lock relaxes that.
The rules are simple:
- Shared read Any number of readers may hold the lock at the same time, because concurrent reads never conflict.
- Exclusive write A writer must hold the lock alone. No other reader or writer may be inside while it writes.
So readers block writers and writers block everyone, but readers do not block other readers. This boosts throughput when reads vastly outnumber writes.
The design has hazards:
- Writer starvation If readers keep arriving, a writer may wait forever. Fair implementations grant a waiting writer priority so new readers queue behind it.
- Reader starvation A write biased policy can instead delay readers.
- Overhead A read write lock is heavier than a plain mutex, so for short critical sections or balanced workloads a simple mutex can be faster.
Use a read write lock when reads dominate and critical sections are long enough that the extra bookkeeping pays off.
Key idea
A read write lock allows many simultaneous readers but gives writers exclusive access, raising throughput for read heavy data while risking writer starvation.