Question

I'm interested in causing a failure in the readers/writers semaphore solution, with writers priority.

In the following code, taken from Wikipedia:

    READER
      P(mutex_3);
        P(r);
          P(mutex_1);
            readcount := readcount + 1;
            if readcount = 1 then P(w);
          V(mutex_1);
        V(r);
      V(mutex_3);

      reading is performed

      P(mutex_1);
        readcount := readcount - 1;
        if readcount = 0 then V(w);
      V(mutex_1);

...there is a binary semaphore mutex_3, which limits number of threads trying to get access to r semaphore, so that writers have priority.

I tried removing that mutex, expecting writers to starve, but didn't succeed. I wrote a program in Java, where threads wait a fixed amount of time twice: after and during reading/writing. I created one writer process and 8 readers processes and set waiting amount to 1 ms for all. I tried creating a situation wherein the r semaphore is being constantly attacked by one writer and many readers. None of this caused the failure I expected.

Am I doing something wrong? How can I cause writer starvation?

Was it helpful?

Solution

In this problem - from wikipedia -

int readcount, writecount; (initial value = 0)
semaphore mutex_1, mutex_2, mutex_3, w, r ; (initial value = 1)

READER
  P(mutex_3);
    P(r);
      P(mutex_1);
        readcount := readcount + 1;
        if readcount = 1 then P(w);
      V(mutex_1);
    V(r);
  V(mutex_3);

  reading is performed

  P(mutex_1);
    readcount := readcount - 1;
    if readcount = 0 then V(w);
  V(mutex_1);


WRITER
  P(mutex_2);
    writecount := writecount + 1;
    if writecount = 1 then P(r);
  V(mutex_2);

  P(w);
    writing is performed
  V(w);

  P(mutex_2);
    writecount := writecount - 1;
    if writecount = 0 then V(r);
  V(mutex_2);

It will be hard in practice to starve Readers, but in theory, they could.

The thing is that Writers have priority over Readers, so if you have Writers coming all the time, the Readers will be waiting for execution for ever.

Hope it helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top