← Lessons

quiz vs the machine

Gold1480

Concurrency

The Readers Writers Problem

Sharing data among many readers and exclusive writers without starvation.

5 min read · core · beat Gold to climb

The Readers Writers Problem

The readers writers problem asks how to coordinate access to shared data where many threads only read and some threads write. Reads do not conflict with each other, so multiple readers can run at once. A write conflicts with everything, so a writer needs exclusive access.

A readers writer lock captures this. It offers a shared mode that any number of readers can hold simultaneously, and an exclusive mode that only one writer can hold while no readers are active. This beats a plain mutex when reads vastly outnumber writes because readers no longer block each other.

The hard part is fairness. There are three policy variants:

  • Reader preference New readers may enter while a writer waits. This maximizes read throughput but can starve writers indefinitely if readers keep arriving.
  • Writer preference Once a writer is waiting, new readers are held back. This protects writers but can starve readers.
  • Fair or no preference Requests are served roughly in order, bounding the wait for both sides.

The right choice depends on workload. A mostly read cache might tolerate reader preference, while a system that must apply updates promptly needs writer preference or fairness.

A subtle danger is lock upgrade, where a thread holding a read lock tries to become a writer. If two readers both attempt this they deadlock, so most implementations forbid upgrading and require releasing the read lock first.

Key idea

A readers writer lock lets many readers share access but gives writers exclusive access, and the chosen preference policy decides whether readers or writers risk starvation.

Check yourself

Answer to earn rating on the learn ladder.

1. Why can multiple readers hold a readers writer lock at once?

2. What is the risk of reader preference?