Readers Writers: Addressing writer starvation

The earlier problem from Readers Writers: Simple Version is because a reader, R1 might have a lock, a writer W is waiting for the lock, and then another reader R2 requests access.

In that scenario, the simple version gives priority to R2.

If reads happen back to back, a writer process will be starved.

To solve this:

readcount = 0
writecount = 0
rmutex = S(1)
wmutex = S(1)
readTry = S(1)
resource = S(1)


reader() {
  wait(readTry); // Indicate a reader is trying to enter
  wait(rmutex); // lock entry section to avoid race condition
  readcount++; // Indicate you are reader
  if (readcount == 1) // if you are first reader, lock the resource
  signal(rmutex) // release entry section for other readers
  signal(readTry) // done trying to access resource
  wait(rmutex); // reserve exit section (avoid race condition)
  readcount--;  // indicate you're leaving
  if (readcount == 0) { // checks if you are last reader leaving
    signal(resource) // release locked resource
  signal(rmutex) // release exit section


writer() {
  wait(wmutex) // reserve entry section for writers - avoid race condition
  writecount++; // report yourself as a writer
  if (writecount == 1) { // If you're the first writer
    wait(readTry); // Lock readers out, prevent them from entering CS
  signal(wmutex) // Release entry section
  wait(resource) // Reserve resource
  // CRITICAL SECTION (writing stuff....)
  signal(resource) // release file

  wait(wmutex); // reserve exit section
  writecount--; // indicate you're leaving
  if (writecount == 0) { // checks if you're the last writer
    wait(readTry); // If you're the last writer, must unlock for other readers
  signal(wmutex); //release exit section

This leads to reader starvation.

We need to merge the 2 approaches