ReadersWriters Problem (original) (raw)

Readers-Writers Problem

Last Updated : 2 Sep, 2025

The Readers-Writers Problem is a classic synchronization issue in operating systems. It deals with coordinating access to shared data (e.g., database, file) by multiple processes or threads.

The challenge is to design a synchronization scheme that ensures:

  1. Multiple readers can access data together if no writer is writing.
  2. Writers have exclusive access no other reader or writer can enter during writing.

Variants of the Problem

**1. Readers Preference

**2. Writers Preference

Solution When Reader Has The Priority Over Writer

Here priority means, no reader should wait if the shared resource is currently open for reading. There are four types of cases that could happen here.

Case Process 1 Process 2 Allowed/Not Allowed
Case 1 Writing Writing Not Allowed
Case 2 Writing Reading Not Allowed
Case 3 Reading Writing Not Allowed
Case 4 Reading Reading Allowed

Synchronization Variables

Semaphore Operations

Reader Process(Reader Preference)

1. Reader requests the entry to critical section.

2. If allowed:

3. If not allowed, it keeps on waiting.

do {

wait(mutex); // Lock before updating readcnt
readcnt++;

if (readcnt == 1)
wait(wrt); // First reader blocks writers
signal(mutex); // Allow other readers in

// ---- Critical Section (Reading) ----

wait(mutex);
readcnt--;
if (readcnt == 0)
signal(wrt); // Last reader allows writers
signal(mutex); // Unlock
} while(true);

**Explanation:

The first reader blocks writers, the last reader allows writers, and all readers in between share the resource. This gives preference to readers, but writers may starve.

Writer’s Process

do {
wait(wrt); // Lock resource

// ---- Critical Section (Writing) ----

signal(wrt); // Release resource
} while(true);

**Explanation:

Only one writer can write at a time, and no readers are allowed while writing. This ensures data integrity.

The Readers-Writers Problem highlights the need for proper synchronization when multiple processes access shared data.