Reader Writer #2 using Semaphore

semaphore_Reader_Writer_2

https://en.wikipedia.org/wiki/Readers%E2%80%93writers_problem

Readers won’t starve Writers anymore

Due to readTry, if additional future reads come in, these future reads wait FCFS with future writes via readTry. Thus, this line gives
fair chance for future writes to grab readTry and do its writing.

Another very important thing is that once a future write grabs readyTry, no future reads will be able to grab readTry. This causes existing reads to eventually finish reading, decreasing readCount back to 0. Once this future write finishes, then the next waiting Read can start again.

Writers may starve Readers

The very first writer has a hold on readyTry so that no other “additional” readers can come in.
When we’re done writing, we decrement. IF WE’RE THE LAST WRITER, make sure to let go of readyTry, so other readers can come in.

However, this starves readers because reader’s first execution is to try to grab readTry. Since its already been held by the first
writer, the reader will fail.

Furthermore, future writers come in and do not need to grab readTry again. It was already held by the first
writer and thus, future writers will simply wait for the resource to do its writing, then decrement writeCount.

ONLY the last writer can let go of readTry. And this is where it starves readers.

Let’s see what happens when a reader X and writer C get executed.

output