Readers Writers Problem

Readers Writers Problem

Readers Writers 1

Problem Statement

Two kinds of concurrent processes share a common data set:

RoleAction
ReaderNeeds read-only access; many readers may read simultaneously.
WriterNeeds exclusive access; no other reader or writer may access the data while a writer is active.

Constraints:

  • Any number of readers may read concurrently.
  • A writer must have exclusive access—no reader or other writer can access the data during a write.

Solution (Readers-Preference)

Synchronization Primitives

SemaphoreInitial ValueMeaning
mutex1Binary semaphore protecting the shared variable readCount.
wrt1Binary semaphore granting writers exclusive access to the data; first reader also waits on it.

readCount (integer) counts active readers. All semaphore operations are atomic.

Shared Data

1int  readCount = 0;    // number of active readers
2semaphore mutex = 1;   // guards readCount
3semaphore wrt   = 1;   // writers (and first/last reader) lock

Reader

 1while (true) {
 2    wait(mutex);               // protect readCount
 3        readCount++;
 4        if (readCount == 1)    // first reader locks writers out
 5            wait(wrt);
 6    signal(mutex);             // release readCount lock
 7
 8    /* ----- critical section (read) ----- */
 9    read_data();
10    /* ----------------------------------- */
11
12    wait(mutex);               // protect readCount
13        readCount--;
14        if (readCount == 0)    // last reader lets writers in
15            signal(wrt);
16    signal(mutex);             // release readCount lock
17
18    remainder_section();
19}

Writer

 1while (true) {
 2    wait(wrt);          // request exclusive access
 3
 4    /* ----- critical section (write) ----- */
 5    write_data();
 6    /* ------------------------------------ */
 7
 8    signal(wrt);        // release exclusive access
 9
10    remainder_section();
11}

How the Semaphores Coordinate the Processes

StepSemaphore ActionEffect
First reader entrywait(mutex)readCount++wait(wrt)Locks out writers; subsequent readers proceed without waiting on wrt.
Additional readerswait(mutex) / signal(mutex)Only update readCount; no writer exclusion needed if readCount > 0.
Last reader exitwait(mutex)readCount--signal(wrt)Re-enables writers when no reader remains.
Writer entry / exitwait(wrt) / signal(wrt)Provides writers with exclusive access; blocks readers when held.

Correctness Achieved

RequirementMechanism
Mutual Exclusionwrt held by either a writer or the reader group (via first reader) ensures no overlap.
No Read–Write ConflictWriters cannot enter while wrt is held by readers; readers cannot start if a writer holds wrt.
Reader ConcurrencyMultiple readers skip wrt once the first reader has locked it, allowing parallel reads.
ProgressIf the data is free, whichever process (reader or writer) obtains the relevant semaphore first proceeds.
Bounded WaitingReaders waiting only contend for mutex; writers wait at most until current readers finish.

This semaphore arrangement (readers-preference variant) maximizes reader concurrency while still guaranteeing writers exclusive access when required.

Readers Writers 2

This is the second classical formulation of the Readers-Writers problem — known as the Writers-Preference solution.

Problem Statement

Two types of concurrent processes — readers and writers — share a common resource (usually a database or file):

RoleGoal
ReadersMay access the resource simultaneously with other readers.
WritersMust have exclusive access — no other readers or writers allowed.

Solution (Writers-Preference)

Synchronization Primitives

SemaphoreInitial ValuePurpose
mutex11Ensures mutual exclusion for readCount.
mutex21Ensures mutual exclusion for writeCount.
readTry1Allows writers to block new readers when they are waiting.
wrt1Actual access control to the shared resource (held exclusively).

Shared Data

1int readCount = 0;      // number of active readers
2int writeCount = 0;     // number of waiting writers
3
4semaphore mutex1 = 1;   // protects readCount
5semaphore mutex2 = 1;   // protects writeCount
6semaphore readTry = 1;  // blocks readers if writer is waiting
7semaphore wrt = 1;      // resource access

Reader Process

 1while (true) {
 2    wait(readTry);           // Check if writers are waiting
 3    wait(mutex1);
 4        readCount++;
 5        if (readCount == 1)  // First reader locks the resource
 6            wait(wrt);
 7    signal(mutex1);
 8    signal(readTry);
 9
10    // ----------- Critical Section (Read) -----------
11    read_data();
12    // -----------------------------------------------
13
14    wait(mutex1);
15        readCount--;
16        if (readCount == 0)  // Last reader releases the resource
17            signal(wrt);
18    signal(mutex1);
19
20    remainder_section();
21}

Writer Process

 1while (true) {
 2    wait(mutex2);
 3        writeCount++;
 4        if (writeCount == 1)   // First writer blocks new readers
 5            wait(readTry);
 6    signal(mutex2);
 7
 8    wait(wrt);                // Lock the resource
 9
10    // ----------- Critical Section (Write) ----------
11    write_data();
12    // -----------------------------------------------
13
14    signal(wrt);
15
16    wait(mutex2);
17        writeCount--;
18        if (writeCount == 0)   // Last writer allows readers again
19            signal(readTry);
20    signal(mutex2);
21
22    remainder_section();
23}

How the Semaphores Coordinate the Processes

StepSemaphore MechanismEffect
Writers signal intentFirst writer locks readTryPrevents new readers from entering if any writer is waiting.
Multiple writers waitAll writers still wait on wrtStill enforces one-writer-at-a-time.
First reader waitsBlocks on readTry if writer is pendingEnforces writer preference.
Last reader unlocksreadCount == 0signal(wrt)Allows writers to proceed once all readers finish.
Last writer unlocks readerswriteCount == 0signal(readTry)New readers are now allowed to proceed.

Correctness Achieved

RequirementMechanism
Mutual Exclusionwrt guarantees only one writer or many readers access the resource at any one time.
Reader ConcurrencyMultiple readers are allowed when no writer is waiting or active.
Writer PreferencereadTry blocks new readers once a writer is waiting, giving writers priority.
No StarvationWriters get access once all active readers finish and new ones are blocked.
Bounded WaitingWriters waiting first will proceed first (FIFO on wrt), and readers are blocked until done.

This version avoids starvation of writers by preventing new readers from entering the critical section once a writer has requested access. It ensures fairness toward writers even in a heavily read-oriented system.

Last updated on