Skip to main content

Readers-writers problem with semaphore

Short answer

The readers-writers problem ensures many readers can read a shared resource simultaneously, but a writer requires exclusive access. A semaphore-based solution uses a mutex to protect the reader count rc, and a db semaphore. The first reader locks db, subsequent readers enter; the last reader unlocks db, allowing waiting writers. This favors readers, possibly starving writers.

Explain the Readers-writers problem. Also explain how this problem can be solved using semaphore.

The problem

A shared database (or file) is used by many processes. Readers only read; writers read and modify it. The rules are:

  • Many readers may read at the same time (reading does not change the data).
  • A writer must have exclusive access: no other reader or writer may be active while it writes.

Without control, a reader could see half-written data, or two writers could corrupt the data.

Solution using semaphores (first readers-writers problem)

Two semaphores and a counter are used: mutex (initially 1) protects the reader count rc; db (initially 1) gives exclusive access to the database.

semaphore mutex = 1;   /* protects the variable rc */
semaphore db    = 1;   /* controls access to the database */
int rc = 0;            /* number of readers currently reading */

void reader() {
    while (TRUE) {
        down(&mutex);
        rc = rc + 1;
        if (rc == 1) down(&db);   /* first reader locks out writers */
        up(&mutex);
        read_database();
        down(&mutex);
        rc = rc - 1;
        if (rc == 0) up(&db);     /* last reader lets writers in */
        up(&mutex);
        use_data_read();
    }
}
void writer() {
    while (TRUE) {
        think_up_data();
        down(&db);                /* exclusive access */
        write_database();
        up(&db);
    }
}
  • The first reader locks db; later readers enter freely. The last reader releases db.
  • A writer must get db, so it waits until all readers have left.
  • A drawback: readers have priority, so a steady stream of readers can starve writers. A writer-priority version (second problem) makes new readers wait if a writer is waiting, but then readers can starve.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Operating System chapter 3 questions →