Synchronization in the classical readers and writers problem can be achieved…

2007

Synchronization in the classical readers and writers problem can be achieved through use of semaphores. In the following incomplete code for readers-writers problem, two binary semaphores mutex and wrt are used to obtain synchronization


wait (wrt)
writing is performed
signal (wrt)
wait (mutex)  
readcount = readcount + 1
if readcount = 1 then S1
S2
reading is performed
S3
readcount = readcount - 1
if readcount = 0 then S4 
signal (mutex)

The values of S1, S2, S3, S4, (in that order) are

  1. A.

    signal (mutex), wait (wrt), signal (wrt), wait (mutex)

  2. B.

    signal (wrt), signal (mutex), wait (mutex), wait (wrt)

  3. C.

    wait (wrt), signal (mutex), wait (mutex), signal (wrt)

  4. D.

    signal (mutex), wait (mutex), signal (mutex), wait (mutex)

Attempted by 149 students.

Show answer & explanation

Correct answer: C

Correct placement for S1, S2, S3, S4:

  1. S1 = wait(wrt) (first reader locks writers): When readcount becomes 1 the reader must acquire the writer semaphore so writers are blocked while any readers are active.

  2. S2 = signal(mutex) (release protection on readcount): After incrementing readcount, release mutex so other readers can update readcount concurrently.

  3. S3 = wait(mutex) (re-acquire to decrement safely): Before decrementing readcount, acquire mutex to protect the update.

  4. S4 = signal(wrt) (last reader releases writers): If readcount becomes 0 after decrement, signal wrt to allow a waiting writer to proceed.

Summary sequence inserted into the reader code:

  • wait(mutex);

  • readcount = readcount + 1;

  • if (readcount == 1) wait(wrt);

  • signal(mutex);

  • /* reading is performed */

  • wait(mutex);

  • readcount = readcount - 1;

  • if (readcount == 0) signal(wrt);

  • signal(mutex);

This ensures that multiple readers can read concurrently while writers are excluded; the mutex protects readcount updates and the writer semaphore enforces exclusive writer access.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir