Skip to content

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

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