This Code Snippet Is An Implementation of The Reader Process in The Readers
This Code Snippet Is An Implementation of The Reader Process in The Readers
semaphores. This problem deals with synchronizing access to a shared resource (typically a database
or file) so that:
Multiple readers can access the resource simultaneously.
A writer requires exclusive access (no other reader or writer can access the resource while
writing).
down(mutex); // (6)
rc = rc - 1; // (7)
if (rc == 0) up(db); // (8)
up(mutex); // (9)
}
🔄 Step-by-Step Explanation
Entry Section (Before Reading):
1. down(mutex);
The reader locks the mutex to safely update the shared rc variable.
2. rc = rc + 1;
Increments the reader count.
3. if (rc == 1) down(db);
o If this is the first reader, it locks the db semaphore to block writers from entering.
o Allows multiple readers to read concurrently once the first reader locks the
database.
4. up(mutex);
Releases the mutex, allowing other readers to update rc.
Critical Section (Reading):
5. db;
Represents the actual reading operation. All readers read concurrently.
Exit Section (After Reading):
6. down(mutex);
Locks the mutex again to safely update rc.
7. rc = rc - 1;
Reader finishes and decrements the reader count.
8. if (rc == 0) up(db);
o If this was the last reader, it unlocks the db semaphore to allow a writer to proceed.
o Ensures that writers get access only when no readers are left.
9. up(mutex);
Releases the mutex, completing the reader's operation.
✅ Summary
This logic ensures:
Multiple readers can read simultaneously.
Writers get exclusive access, but only when no readers are reading.
Mutual exclusion is maintained for rc updates using mutex.