I have a homework problem where I have to implement a reader writer lock. Please note that I am NOT looking/asking for code. I wish to understand the behaviour of reader-writer locks which will help me finalize the implementation details.
Lets say the request for acquiring the locks follows this sequence: R W R W R W R W..
In order to prevent starvation, should we process the requests in the same order? If I choose to jump over a write request (thus giving readers a higher preference), how can I ensure that a writer thread will not starve?
If give writers a higher preference instead, I think there is chance that reader threads will starve.
I think my current plan will work for sequences like RRRRWRRRRWWWRRRRR, WWWWWWRRRRWRRRR, RRRRRRR, WWWWWWW, RWRRR, WRWWWW and so on.
Are there any other scenarios I am not considering? – I know this is a tough one to answer esp. since I am not disclosing any details and haven’t enumerated all scenarios I considered. Please bear with me!
“Higher priority” can only produce starvation when there is no bound on the wait time.
If the amount of time for which any thread can wait is bounded to some finite value, that thread will not starve.
So, as long as you keep track of when threads enter the queue and somehow don’t let them wait “too long”, you can “prioritize readers over writers” in the general case (or the reverse), while still not causing a livelock.
The same effect can be gotten by only servicing a maximal number of readers before taking a writer, or vice versa.