Course contentsShow
← Computer Science
Lesson 1299 of 2,87230. Process SynchronizationFree lesson

Readers-Writers Problem with Semaphores

Implementing solutions to the readers-writers problem using semaphores for coordinated access.

Readers-Writers Problem with Semaphores

What you'll learn: How to use semaphores to coordinate multiple readers and writers accessing shared data without conflicts.

The Problem

Imagine a library database: many people can read records simultaneously without causing issues, but when someone writes (updates a record), no one else should be reading or writing at the same time. This is the readers-writers problem—allowing concurrent reads while ensuring exclusive writes.

Core Solution Strategy

We use semaphores to enforce two rules:

  1. Multiple readers can access the data simultaneously (no mutual exclusion among readers)
  2. Writers need exclusive access (no readers or other writers present)

First Readers-Writers Solution

We typically use:

  • A counting semaphore (wrt) initialized to 1 for writer exclusion
  • A mutex (mutex) to protect the reader count
  • An integer read_count tracking active readers

Reader logic:

  • First reader arriving acquires wrt (blocks writers)
  • Subsequent readers just increment the count
  • Last reader leaving releases wrt (allows writers)

Writer logic:

  • Simply acquires wrt for exclusive access
  • Releases wrt when done

The Analogy

Think of a museum exhibit room: any number of visitors (readers) can view simultaneously, but when a curator (writer) needs to rearrange displays, the room must be completely empty and locked.

Fairness Considerations

This "readers-preference" solution can starve writers if readers continuously arrive. The writer must wait until all readers finish, and new readers can still enter while others are reading.

Key Takeaway: Semaphores solve the readers-writers problem by letting the first reader lock out writers and the last reader unlock, enabling concurrent reads while maintaining write exclusivity—though fairness requires additional mechanisms.