← Concepts

阅读中文版本

Reader-Writer Locks

Reader-writer locks allow concurrent readers or one exclusive writer, improving read-parallelism — but writer starvation, recursive hazards, and read-side caching effects often eat the gains.

concurrency

Definition

A reader-writer lock distinguishes shared acquisition for readers and exclusive acquisition for writers. Many readers hold the lock simultaneously; a writer excludes everyone. Policy decides who wins when readers and writers queue: reader preference starves writers, writer preference stalls readers; fair variants hand off in arrival order.

Context and scope

Used for read-mostly shared state: configuration snapshots, caches, registries. Compared against RCU, seqlocks, and atomic snapshot copies, which scale far better on many cores.

Common misconceptions

  • Reader-writer locks are always faster than mutexes — under short critical sections or many cores, lock bookkeeping and cache-line bouncing can make them slower
  • Upgrading a read lock to write is safe — upgrades race between upgraders; most implementations fail or deadlock there
  • Reentrant read acquisition is risk-free — recursive read holding breaks release-once logic in several implementations

Anti-patterns

  • Reader-preference locks protecting state that writers must update within deadlines
  • Holding read locks across callbacks or I/O and serializing writers behind slow readers
  • Choosing rwlock by instinct instead of benchmarking against a plain mutex and an immutable snapshot swap

Related concepts

Related examples

Authoritative source

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

What it is

Mutual exclusion wastes parallelism when workloads are overwhelmingly reads. The rwlock splits the contract: readers share, writers exclude. The semantics are simple; the policy and performance story is not.

How it works

State tracks reader count and writer presence. Acquire-read increments under synchronization; acquire-write waits for zero readers. Arrival policy determines starvation behavior: unfair reader preference lets writers wait indefinitely under continuous read traffic. Upgrade attempts race — two readers both requesting write deadlock or fail unless the implementation handles it explicitly.

When to use it

Read-mostly data with non-trivial critical sections and moderate core counts. For configuration and caches, compare against atomic pointer swap of immutable snapshots — often simpler and faster, with readers paying no lock cost.

Pitfalls

The lock word itself is a contention point: every reader acquisition dirties the cache line, so scaling collapses on many cores where RCU or seqlocks thrive. Holding read locks across unknown callbacks risks deadlock when callbacks write. Write-lock recursion deadlocks in common implementations.