Readers–Writers Problem with Writer Priority Using Semaphores
Readers–Writers Problem with Writer Priority Using Semaphores
1. Aim
To implement the Readers–Writers process synchronization problem using semaphores, ensuring that writers are given priority over readers while accessing a shared resource.
2. Objectives
-
To study process synchronization using semaphores.
-
To understand writer priority in the Readers–Writers problem.
-
To prevent writer starvation while allowing concurrent readers.
-
To implement synchronization using POSIX threads and semaphores.
3. Problem Description
In a shared system:
-
Readers only read shared data.
-
Writers modify shared data.
-
Multiple readers may read simultaneously.
-
Writers require exclusive access.
-
If a writer is waiting, new readers must wait (writer priority).
4. Theory
Process Synchronization
Process synchronization ensures that multiple processes/threads operate on shared resources without conflicts, maintaining data consistency.
Readers–Writers Problem
This is a classical synchronization problem where:
-
Readers can share access to the resource.
-
Writers must access the resource exclusively.
-
Priority policies decide whether readers or writers get preference.
Writer Priority
In the writer-priority solution:
-
Writers are allowed to proceed as soon as the resource becomes free.
-
Incoming readers must wait if any writer is waiting.
-
This prevents writer starvation.
5. Synchronization Tools Used
Semaphores
Semaphores are synchronization variables supporting two atomic operations:
-
wait()(P operation) -
signal()(V operation)
6. Semaphores and Shared Variables
| Name | Type | Purpose |
|---|---|---|
mutex | Binary | Protects the reader count |
rw_mutex | Binary | Controls access to the shared resource |
queue | Binary | Enforces writer priority |
read_count | Integer | Number of active readers |
7. Algorithm
Reader Algorithm (Writer Priority)
-
Wait on
queue -
Wait on
mutex -
Increment
read_count -
If
read_count == 1, wait onrw_mutex -
Signal
mutex -
Signal
queue -
Read the shared data
-
Wait on
mutex -
Decrement
read_count -
If
read_count == 0, signalrw_mutex -
Signal
mutex
Writer Algorithm (Writer Priority)
-
Wait on
queue -
Wait on
rw_mutex -
Write to the shared data
-
Signal
rw_mutex -
Signal
queue
8. C Program Implementation
(POSIX Threads + Semaphores)
Compilation
9. Sample Output
10. Observations
-
Multiple readers read simultaneously.
-
Writers write one at a time.
-
When a writer is waiting, no new reader enters.
-
Writer starvation is avoided.
Comments
Post a Comment