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
(A) signal (mutex), wait (wrt), signal (wrt), wait (mutex)
(B) signal (wrt), signal (mutex), wait (mutex), wait (wrt)
(C) wait (wrt), signal (mutex), wait (mutex), signal (wrt)
(D) signal (mutex), wait (mutex), signal (mutex), wait (mutex)
Answer: (C)
Explanation: For S1: if readcount =1 => reader is reading now, so no writer must execute. Hence, S1 has to be wait(wrt)
For S2: After readcount has been updated, is made to 1, so other readers can enter into entry section. Multiple readings are allowed. (Only 1 at a time can be in entry section ) hence signal(mutex)
For S3: Now at a time only one process can be in Exit section and semaphore mutex is used to implement it (only 1 at a time can be in exit section).Hence wait(mutex)
For S4: If readcount is zero i.e no reader is reading, means last reader has completed reading, it should unlock resources so that any writer waiting for it can use it .hence signal(wrt).The above values of S1, S2, S3, and S4 are all nothing but implementing first reader writer problem.
References:
Readers-writers-problem-set-1-introduction-and-readers-preference-solution/
https://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/6_Synchronization.html
This solution is contributed by Nitika Bansal
Related Concepts:
Process Synchronization|Set1
Mutex Vs Semaphore
Monitors
Readers-writers_problem (Wikipedia)
Quiz of this Question