Operating System - Reader-Writer Problem

 What is the Reader-Writer Problem?

The Reader-Writer Problem deals with a shared resource (like a file or database) that can be accessed by multiple readers or writers.

  • Readers: Only read the shared data (no modification).

  • Writers: Read and write (modify) the shared data

  • Problem: If multiple processes access the data simultaneously (especially writers), it can cause data inconsistency.

Goal

  • Multiple readers can read the shared resource at the same time.

  • Only one writer can write, and no reader should read while writing.

  • Prevent race conditions, starvation, and data corruption.

 Conditions to Maintain

Operation Is Concurrent Access Allowed?
Readers ↔ Readers    Yes – multiple readers allowed
Writers ↔ Writers    No – only one writer at a time
Readers ↔ Writers    No – cannot mix readers and writers

 Real-World Example:

Imagine a library book:

  • Many people can read it at the same time (if they’re just reading and not writing in it).

  • But if one person is editing or writing in the book, no one else should access it.

 Reader-Writer Problem Variants

There are three classical versions of the problem based on fairness:

1. First Readers-Writers Problem (Reader Priority)

  • Readers are given priority.

  • A writer may starve if readers keep coming.

2. Second Readers-Writers Problem (Writer Priority)

  • Writers are given priority.

  • Readers may have to wait until no writers are waiting.

3. Fair Solution (No Starvation)

  • Ensures neither readers nor writers starve.

  • Uses a fair queuing mechanism.

Advantages of a Good Solution

  • Data integrity is maintained.

  • Concurrency is optimized (readers can read in parallel).

  • Starvation prevention if fairness is ensured.

Disadvantages

  • Starvation of writers or readers depending on priority.

  • Deadlock if semaphores are misused.

  • Busy waiting in some naive implementations.