Read-write lock¶
Category: Synchronization · Status: stub · Lessons: chapter 02, Shared state
One line: A lock that lets many readers in at once but lets a writer in only alone.
Also called: RwLock, shared-exclusive lock, shared lock, readers-writer lock, RWMutex, shared_mutex.
How it connects¶
flowchart LR
n_mvcc["Multi-version concurrency control"]
n_mutex["Mutex"]
n_rcu["Read-copy-update"]
n_read_write_lock["Read-write lock"]
n_starvation["Starvation"]
n_mvcc ---|or| n_read_write_lock
n_rcu ---|or| n_read_write_lock
n_read_write_lock -->|can cause| n_starvation
n_read_write_lock -->|is a| n_mutex
classDef center stroke-width:3px
class n_read_write_lock center
classDef outside stroke-dasharray: 4 3
class n_mvcc,n_mutex,n_rcu,n_starvation outside
- Is a kind of: Mutex
- Can lead to: Starvation
- An alternative to: Multi-version concurrency control, Read-copy-update
- See also: Classic synchronization problems
In each language¶
| Rust | RwLock ↗: the reader-writer priority policy is left to the operating system, and taking it again on the same thread might panic |
| Go | sync.RWMutex ↗: a waiting writer blocks new readers, which rules out recursive read-locking; RLock cannot be upgraded to Lock |
| C++ | std::shared_mutex ↗ (C++17): shared access for readers, exclusive for a writer |
| Java | ReentrantReadWriteLock ↗ with an optional fair mode; StampedLock ↗ adds optimistic reads but is not reentrant |
| C# | ReaderWriterLockSlim ↗, which by default does not allow recursion |
| The operating system | POSIX pthread_rwlock_rdlock ↗: a reader gets the lock if no writer holds it and no writers are blocked on it |
Where to read more¶
- In a sibling library: Rust: RwLock and atomics ↗
- In the books: Hands-On Concurrency with Rust, Brian L. Troutwine — ch. 5, 'Locks – Mutex, Condvar, Barriers and RWLock'
- In the books: Learn Concurrent Programming with Go, James Cutajar — ch. 4, 'Synchronization with mutexes' → 'Improving performance with readers–writer mutexes'
- In the books: Pthreads Programming, Bradford Nichols, Dick Buttlar, Jacqueline Proulx Farrell — ch. 3, 'Synchronizing Pthreads' → 'Reader/Writer Locks'
- In the books: Concurrent Programming on Windows, Joe Duffy — ch. 6, 'Data and Control Synchronization' → 'Reader/Writer Locks (RWLs)'
- In the books: The Little Book of Semaphores, Allen B. Downey — ch. 4, 'Classical synchronization problems' → 'Readers-writers problem'
- In the books: Rust Atomics and Locks, Mara Bos — ch. 1, 'Basics of Rust Concurrency' → 'Locking: Mutexes and RwLocks'
- Reference: Wikipedia: Readers–writer lock ↗