← Lessons

quiz vs the machine

Gold1480

Concurrency

Read Write Lock Implementation

A lock that allows many concurrent readers but exclusive access for a single writer.

5 min read · core · beat Gold to climb

Readers share, writers do not

A read write lock separates two access modes. Many threads can hold the read lock at once because reads do not conflict. Only one thread can hold the write lock, and while it does no readers are allowed.

Tracking the state

  • A reader count records how many readers currently hold the lock.
  • A writer flag records whether a writer is active.
  • A new reader may enter only if no writer holds or is granted the lock.
  • A writer may enter only when the reader count is zero and no other writer is active.

The fairness problem

If readers keep arriving, a writer can wait forever, called writer starvation. Fair implementations block new readers once a writer is waiting, so the writer eventually proceeds. This trades a little read throughput for progress guarantees.

Key idea

A read write lock admits concurrent readers but an exclusive writer by tracking a reader count and a writer flag; fair variants block incoming readers when a writer waits to prevent writer starvation.

Check yourself

Answer to earn rating on the learn ladder.

1. What does a read write lock allow simultaneously?

2. What is writer starvation?

3. How do fair read write locks prevent writer starvation?