The Readers–Writers Problem
Understand the classic Readers–Writers synchronization problem
Background
The Readers–Writers problem is a classic synchronization problem in operating systems and concurrent programming. It models a situation where a shared resource (for example, a database, a file, or an in-memory data structure) is accessed by two kinds of processes/threads:
- Readers — threads that only read the shared data and never modify it.
- Writers — threads that modify the shared data.
Problem Statement
Multiple threads share a single resource. We must coordinate their access so that the resource stays consistent, subject to the following rules:
- Multiple readers may read at the same time. Because reading does not change the data, any number of readers can safely access the resource concurrently.
- A writer requires exclusive access. While a writer is modifying the resource, no other thread — reader or writer — may access it. This prevents readers from seeing a partially-updated (inconsistent) value and prevents two writers from corrupting each other’s updates.
In short:
| Currently active | A new reader may enter? | A new writer may enter? |
|---|---|---|
| Nobody | Yes | Yes |
| One or more readers | Yes | No |
| A writer | No | No |
The Synchronization Challenge
A naive solution that simply locks the resource for every access would be correct but slow — it would force readers to wait for one another even though concurrent reads are safe. The real challenge is to allow maximum reader concurrency while still guaranteeing exclusive writer access.
Variants
Different fairness policies lead to different variants of the problem:
- First readers–writers (readers-preference): No reader is kept waiting unless a writer has already obtained permission to use the resource. The downside is that a continuous stream of readers can starve writers — a writer may wait forever.
- Second readers–writers (writers-preference): Once a writer is waiting, no new reader is allowed to start until the writer has finished. This can starve readers.
- Third readers–writers (no starvation / fair): Neither readers nor writers starve. Requests are typically served in arrival order using an additional queueing lock, so a writer only waits for readers already inside and new readers queue behind the writer.
Requirements of a Correct Solution
A valid solution must satisfy:
- Mutual exclusion for writers — at most one writer accesses the resource at a time, and no reader overlaps with a writer.
- Reader concurrency — several readers can read simultaneously.
- No deadlock — the system never reaches a state where every thread is waiting on another.
- (Ideally) No starvation — every thread eventually gets to access the resource.
This Assignment
The accompanying C program (reader_writer.c) implements a solution using
POSIX threads (pthreads). It demonstrates the classic semaphore/mutex based
approach and includes notes on how to bias it toward readers or writers.