Sub topic 13
The readers-writers problem
This chapter assumes you know what a race condition is, what the critical-section problem requires (mutual exclusion, progress, bounded waiting), and how wait and signal work on binary and counting semaphores. It also assumes you can read C-like pseudocode.
The problem
Several processes share a data set, such as a database record or a file. Some only read it. Others write it.
- Any number of readers may be inside at the same time, because reading does not change the data.
- A writer must be alone. If a writer overlaps with a reader or with another writer, the reader may see half-updated data and two writers may corrupt each other's updates.
The rules form a compatibility table.
| Already inside | A reader arrives | A writer arrives |
|---|---|---|
| Nothing | Enters | Enters |
| One or more readers | Enters | Must wait |
| One writer | Must wait | Must wait |
A plain mutex would be correct but too strict. It would serialise the readers too, which wastes the parallelism that read-mostly workloads offer. The readers-writers problem asks for a lock that allows reader concurrency and still keeps writers exclusive.
The first readers-writers solution (readers' preference)
The solution uses two semaphores and one counter.
rwis a binary semaphore initialised to 1. Whoever holds it has the right to use the data in its role. A writer holds it for the whole write. The readers as a group hold it.mutexis a binary semaphore initialised to 1. It protectsreadcount, which is a shared variable.readcountis the number of readers currently inside. It starts at 0.
semaphore rw = 1;
semaphore mutex = 1;
int readcount = 0;
void writer(void) {
wait(rw);
write_data();
signal(rw);
}
void reader(void) {
wait(mutex);
readcount++;
if (readcount == 1) wait(rw);
signal(mutex);
read_data();
wait(mutex);
readcount--;
if (readcount == 0) signal(rw);
signal(mutex);
}The idea is that the first reader locks out writers on behalf of all readers. The last reader to leave lets writers in again. Readers that arrive while others are reading do not touch rw. They only increment the counter and go straight in.
Why `mutex` is needed
readcount++ and readcount-- are read-modify-write operations. Without mutex, two readers could both read the same old value and write back the same new value, so the count would be wrong. If the count drifted to 0 while a reader was still inside, a writer would be admitted early. If it never returned to 0, writers would be locked out for good. This is the race condition from the earlier chapters, applied to the counter.
Why the `wait(rw)` happens while holding `mutex`
Look at the first reader. It calls wait(rw) while it still holds mutex. If a writer is active, the first reader blocks on rw and keeps mutex. Every other reader that arrives then blocks on mutex, not on rw. That is intended. The waiting readers queue up behind the first one, and when the writer finishes, the first reader gets rw, releases mutex, and the queued readers pass through one by one.
Tracing an example
Let R1, R2 and W1 be processes. Initially rw = 1, mutex = 1, readcount = 0.
- R1 arrives. It takes
mutex, setsreadcount = 1, callswait(rw)(now 0), releasesmutex, and starts reading. - W1 arrives. It calls
wait(rw), finds 0 and blocks. - R2 arrives. It takes
mutex, setsreadcount = 2, does not touchrwbecause the count is not 1, and releasesmutex. R2 reads at the same time as R1, even though W1 is already waiting. - R1 finishes.
readcountbecomes 1, so it does not signalrw. - R2 finishes.
readcountbecomes 0, so it callssignal(rw). W1 wakes and writes.
Step 3 is the key. A waiting writer does not stop new readers from joining.
Checking the three requirements
This is the kind of verification GATE questions ask for.
- Mutual exclusion (for writers). A writer holds
rwfor its whole write, and readers as a group holdrwwhilereadcount > 0. So a writer never overlaps with a reader or another writer. Readers overlapping with each other is allowed by the problem. - Progress. If no one is inside, the first arriving process finds
rw = 1and proceeds. Nothing blocks it for no reason. - Bounded waiting. This fails for writers. A writer can wait forever if readers keep arriving so that
readcountnever drops to 0.
Starvation
Starvation means a process is ready to run but is never given the resource. In this solution a writer starves under a steady stream of overlapping readers. This is why the solution is called readers-preference. It maximises read concurrency at the cost of writer fairness.
The second solution (writers' preference)
Here a writer that is waiting blocks any new reader, so writers do not starve. The cost is that readers can now starve if writers keep arriving. This version needs more semaphores and counters. The common textbook form has these pieces.
- A counter of waiting or active writers, protected by its own mutex.
- A semaphore that readers must pass before they can try for the data. The first writer closes it and the last writer reopens it.
You do not need to memorise the full code. You do need to know what it trades. Each preference policy fixes one kind of starvation and exposes the other.
The third approach: a fair solution
A fair solution keeps the arrival order of requests, for example with a FIFO queue or a "turnstile" semaphore that every reader and writer passes through first. A reader then admits itself, and a writer waits for the readers already inside. Because the turnstile queue is first-come first-served (when the semaphore implementation uses a FIFO wait queue), no one waits forever. Throughput drops a little, because a reader behind a waiting writer cannot join the readers already inside.
| Policy | Readers starve? | Writers starve? | Read concurrency |
|---|---|---|---|
| Readers' preference (first problem) | No | Yes | Highest |
| Writers' preference (second problem) | Yes | No | Lower |
| Fair (turnstile or FIFO) | No | No | Moderate |
Common errors
- Dropping
mutex. Updatingreadcountwithout protection gives lost updates, as explained above. - Checking
readcountoutsidemutex. Reading the value aftersignal(mutex)is a race, because another reader may change it first. The solution testsreadcount == 1andreadcount == 0inside the critical section for this reason. - Having readers call
wait(rw)every time. This serialises the readers and removes the point of the solution. - Letting any reader (not the last) signal
rw. A writer would enter while other readers are still inside. - Assuming a waiting writer blocks new readers. It does not in the first solution.
- Reversing the two waits in the entry code. If a reader did
wait(rw)first andwait(mutex)after, the counter would no longer be protected for the first-reader check.
Related constructs
Many systems provide this pattern directly as a reader-writer lock. POSIX offers pthread_rwlock_t with pthread_rwlock_rdlock, pthread_rwlock_wrlock and pthread_rwlock_unlock. Which preference it uses depends on the implementation and its attributes, so check the documentation before relying on it.
Exercise
In the first readers-writers solution, three readers R1, R2 and R3 are reading, and a writer W is blocked. A fourth reader R4 arrives. What happens to R4, and what must happen before W can run?
Show answer
R4 enters immediately. It takes mutex, raises readcount to 4, does not touch rw and reads. W stays blocked on rw. W can run only after readcount falls to 0, which means all four readers must leave. The last one to leave calls signal(rw).
Exercise
Suppose a programmer removes wait(mutex) and signal(mutex) from the reader code and leaves the rest unchanged. Describe an interleaving that breaks the program.
Show answer
Let readcount be 0. Readers R1 and R2 both execute readcount++ as load, add, store. Both load 0, both store 1. The count is 1 although two readers are inside. Both see readcount == 1 and call wait(rw). The second call blocks forever or, depending on timing, the count ends wrong when they leave: the first one to leave sets the count to 0 and signals rw while the other reader is still reading, so a writer can enter during a read. Either outcome breaks the rules.
Exercise
Which of the three critical-section requirements does the first readers-writers solution violate, and for which kind of process?
Show answer
Bounded waiting, for writers. A continuous stream of overlapping readers keeps readcount above 0, so rw is never signalled and a writer can wait forever.