Generally, if two semaphores are acquired one after the other, is there difference between releasing them in the same order or the reverse order as they are acquired?
In the following solution to the third readers-writers problem from http://en.wikipedia.org/wiki/Readers%E2%80%93writers_problem#Third_readers%E2%80%93writers_problem,
in
reader(), why areserviceQueueandrmutexreleased in the same order as they are acquired?does it matter whether
serviceQueueandrmutexare released in the same or reverse order as they are acquired?How does the code improves over the code for the first readers-writers problem, in avoiding starving a writer?
Is
serviceQueuea counting semaphore? what shall it be initialized to?
Code:
int readcount; // init to 0; number of readers currently accessing resource // all semaphores initialised to 1 semaphore resource; // controls access (read/write) to the resource semaphore rmutex; // for syncing changes to shared variable readcount semaphore serviceQueue; // FAIRNESS: preserves ordering of requests (signaling must be FIFO) //READER reader() { <ENTRY Section> serviceQueue.P(); // wait in line to be serviced rmutex.P(); // request exclusive access to readcount readcount++; // update count of active readers if (readcount == 1) // if I am the first reader resource.P(); // request resource access for readers (writers blocked) serviceQueue.V(); // let next in line be serviced rmutex.V(); // release access to readcount <CRITICAL Section> //reading is performed <EXIT Section> rmutex.P(); // request exclusive access to readcount readcount--; // update count of active readers if (readcount == 0) // if there are no readers left resource.V(); // release resource access for all rmutex.V(); // release access to readcount } //WRITER writer() { <ENTRY Section> serviceQueue.P(); // wait in line to be serviced resource.P(); // request exclusive access to resource serviceQueue.V(); // let next in line be serviced <CRITICAL Section> // writing is performed <EXIT Section> resource.V(); // release resource access for next reader/writer }