← Concepts

阅读中文版本

Read-Write Lock

A read-write lock allows many concurrent readers or one exclusive writer, raising throughput for read-heavy shared state.

concurrency

Definition

A read-write lock separates two access modes: any number of readers may hold the lock simultaneously, but a writer requires exclusive access and excludes all readers. It models the common pattern where data is read far more often than it is modified. The gain over a plain mutex is concurrency among readers; the costs are added bookkeeping, a risk of writer starvation under constant read pressure, and the need for policies to decide who goes next.

Context and scope

Protecting caches, configuration, and in-memory indexes that are read on every request but updated rarely.

Common misconceptions

  • Read-write locks are always faster — for short critical sections with frequent writes, lock overhead can outweigh the benefit
  • Readers and writers proceed concurrently — only readers among themselves do; a writer excludes everyone
  • Writer starvation is impossible — under continuous read load, naive implementations may never grant the writer the lock

Anti-patterns

  • Upgrading a read lock to a write lock atomically, which most implementations do not support and which deadlocks
  • Using a read-write lock to guard a critical section that is already trivially short
  • Holding a read lock while performing I/O that may need the write lock, creating a circular wait

Related concepts

Related examples

Authoritative source

https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock

What it is

A read-write lock exposes two acquire modes. In read mode, a caller joins a group of simultaneous readers. In write mode, a caller demands sole access, waiting until all readers have left and blocking new ones. Release distinguishes the mode so the implementation can track reader counts. The data protected is assumed to tolerate many concurrent observers but require isolation for mutation.

Why it matters

Many shared structures — routing tables, feature flags, caches — are read on every request and written occasionally. A plain mutex serialises those reads and becomes the bottleneck as cores and traffic grow. A read-write lock restores parallel read throughput while still making updates safe, which is often the difference between a lock that scales and one that does not.

How to use it well

Reserve it for state genuinely dominated by reads; when writes are frequent, a plain mutex or a lock-free approach is simpler and faster. Prefer implementations with fair or writer-preferring policies so a burst of readers cannot starve updates. Never upgrade a read lock in place — release and re-acquire in write mode, re-validating the data. Consider immutable snapshots with copy-on-write, which let readers proceed with no lock at all.