Hello! Welcome back to your course on Operating Systems.
In our previous lesson, we implemented a semaphore-based solution for the Producer-Consumer problem. We saw how a combination of counting and binary semaphores can manage resource access and prevent deadlock, particularly noting the importance of the order of wait operations.
Today, we're tackling another classic synchronization challenge: the Readers-Writers Problem. This problem introduces a different set of constraints that are common in systems like database management and file access. Our learning outcome is to analyze the Readers-Writers problem using semaphores and identify potential starvation issues. Mastering this analysis is a key skill for answering advanced synchronization questions on the GATE exam.
1. Defining the Readers-Writers Problem
Imagine a shared database or file. We have two types of processes:
- Readers: These processes only read the data. They don't modify it.
- Writers: These processes modify or update the data.
The synchronization constraints are:
- Multiple readers are allowed to read the shared data at the same time.
- A writer must have exclusive access. When a writer is accessing the data, no other process (reader or writer) can be in the critical section.
To understand why this is a synchronization challenge, let's watch a short video that clearly outlines the scenarios we need to manage.
GATE 2023 EXAM | CSE | Operating Systems | Reader-Writer Problem & Solution | Free Online Course
This video from BYJU'S Exam Prep explains the core challenge of the Readers-Writers problem and identifies the three specific concurrent access scenarios that our solution must prevent.
Watch from 02:59 to 05:50. Focus on which combinations of readers and writers cause problems (inconsistency) and which one is perfectly safe.
As the video explained, the problematic cases are Read-Write, Write-Read, and Write-Write. Our goal is to design a system that prevents these while allowing the Read-Read scenario to happen concurrently.
2. A Semaphore Solution: The Reader's Preference Model
A common way to solve this problem is by using semaphores. This solution requires one integer variable and two binary semaphores:
readcount: An integer to keep track of how many readers are currently in the critical section. Initialized to 0.mutex: A binary semaphore to ensure mutual exclusion when updatingreadcount. Initialized to 1.wrt: A binary semaphore that writers use to gain exclusive access. It's also used by the first reader to lock out any writers. Initialized to 1.
Here is the pseudocode for the reader and writer processes. This structure is fundamental and frequently appears in GATE questions.
Writer Process:
while (true) {
wait(wrt);
// ... Critical Section: Writing is performed ...
signal(wrt);
}
Reader Process:
while (true) {
// --- Entry Section ---
wait(mutex);
readcount++;
if (readcount == 1) {
wait(wrt); // First reader in locks out writers
}
signal(mutex);
// ... Critical Section: Reading is performed ...
// --- Exit Section ---
wait(mutex);
readcount--;
if (readcount == 0) {
signal(wrt); // Last reader out allows writers in
}
signal(mutex);
}
Let's break down the logic:
- Writer: The writer's logic is simple. It must acquire the
wrtlock before writing. This single semaphore ensures that only one writer can be in the critical section and that no readers can enter while a writer is active (as we'll see below). - Reader (Entry): The first reader to arrive (
readcount == 1) is responsible for locking thewrtsemaphore. This blocks any waiting writers. Subsequent readers incrementreadcountbut don't need to touchwrt, as it's already locked. Themutexsemaphore is crucial here to prevent a race condition on thereadcountvariable itself. - Reader (Exit): The last reader to leave (
readcount == 0) is responsible for releasing thewrtlock, which allows a waiting writer to finally enter its critical section.
To see this logic in action, let's trace through the execution step-by-step.
GATE 2023 EXAM | CSE | Operating Systems | Reader-Writer Problem & Solution | Free Online Course
This video provides an excellent, detailed walkthrough of the reader and writer code. It simulates how the semaphore values and readcount change as processes enter and exit the critical section.
Watch from 05:50 to 24:31. The first part (until 18:06) covers the entry logic for all three problem cases. The second part (from 18:06) explains the exit section and why the mutex is necessary there. Pay close attention to how the if (readcount == 1) and if (readcount == 0) conditions are the keys to the entire solution.
3. The Flaw in the "Reader's Preference" Solution: Starvation
This solution works correctly in terms of preventing data inconsistency. However, it has a significant fairness problem. Notice that as long as at least one reader is in the critical section, new readers can keep entering, but no writer can get in. This can lead to starvation.
To understand what this means, let's explore a scenario where a writer is blocked indefinitely.
This article from the OpenCSF project explains the concept of writer starvation in the solution we just discussed. It provides a clear scenario and diagram to illustrate how a continuous stream of readers can block a writer forever.
Read the section 'Fairness to Writers'. Focus on the explanation of Figure 8.4.1, which shows how two readers can conspire to lock out a writer indefinitely. The text also introduces a potential fix using a 'turnstile', but your main goal is to understand the starvation problem itself.
In summary, the solution we've analyzed gives preference to readers. If there is a constant stream of incoming readers, a writer might have to wait forever. This is a crucial point of analysis for the GATE exam, where questions often ask you to evaluate the properties (like fairness or freedom from starvation) of a given synchronization algorithm.
Test your understanding!
Analyze the code in the image below, which represents the standard Reader's Preference solution. Is this solution susceptible to starvation? If so, which process type (reader or writer) is at risk of starvation, and under what conditions?
Show answer
Yes, this solution is susceptible to starvation.
The writer process is at risk of starvation.
This happens if there is a continuous stream of reader processes arriving. For example:
- Reader R1 enters.
readcountbecomes 1. R1 executeswait(wrt), acquiring the lock. - A Writer W1 arrives. It executes
wait(wrt)and blocks. - Reader R2 arrives. It passes the
wrtcheck becausereadcountis already greater than 0. It enters the critical section.readcountis now 2. - Reader R1 leaves.
readcountbecomes 1. Sincereadcountis not 0,signal(wrt)is not called. - Reader R3 arrives before R2 leaves. It enters, and
readcountgoes back to 2.
As long as there is always at least one reader in the critical section, readcount will never become 0. Consequently, the signal(wrt) call in the reader's exit section will never be executed, and the waiting writer W1 will be starved.
4. Applying the Concepts to a GATE Problem
Now, let's put your understanding to the test with a real GATE question. This question presents the code structure and asks you to fill in the missing semaphore operations. This is a very common format that tests your deep understanding of the logic flow.
GATE 2023 EXAM | CSE | Operating Systems | Reader-Writer Problem & Solution | Free Online Course
This final segment of the BYJU'S video presents and solves a previous year's GATE question based directly on the reader-writer code we've just studied. Try to solve it yourself before watching the explanation.
Watch from 25:27 to 34:03. The video presents the question first. Pause and try to determine the correct operations for S1, S2, S3, and S4 based on our discussion. Then, watch the detailed explanation to check your reasoning.
Conclusion
In this lesson, we dissected the Readers-Writers problem, a more complex synchronization scenario than the Producer-Consumer problem. We analyzed the standard "reader's preference" solution and, most importantly, identified its critical flaw: the potential for writer starvation.
Key Takeaways:
- The Readers-Writers problem allows concurrent access for readers but requires exclusive access for writers.
- The standard semaphore solution uses a
readcountvariable, amutexto protect it, and awrtsemaphore for writer exclusion. - The first reader to enter the critical section locks out writers, and the last reader to leave allows them in.
- This reader-preference model is not fair and can lead to writer starvation if readers continuously occupy the critical section.
We've now seen how improper semaphore usage can lead to deadlock (in the Producer-Consumer problem) or starvation (in the Readers-Writers problem). In our next lesson, we will begin a new module dedicated to Deadlock. We will formally define the four necessary conditions for deadlock to occur and learn how to model and detect it using Resource Allocation Graphs.