Reader-Writer with Writer Starvation (From Peterson/Galvin)

Reader Entry                 Writer Entry

P(mutex);                         P(wsem)
  rc++;
  if rc=1 then P(wsem);
V(mutex);



Reader Exit                   Writer Exit

P(mutex);                         V(wsem)
  rc--;  
  if rc=0 then V(wsem);
V(mutex);

Reader-Writer with Writer Starvation

Reader Entry

P(rsem);
V(rsem)
P(rmutex);
 rc++
 if rc=1 then P(wsem);
V(rmutex);



Reader Exit

P(rmutex);
 rc--;
 if rc=0 then V(wsem);
V(rmutex);

Writer Entry

P(wmutex);
 wc++;
 if wc=1 then P(rsem);
V(wmutex);
P(wsem);



Writer Exit

V(wsem);
P(wmutex);
  wc--;
  if wc=0 then V(rsem);
V(wmutex);

Reader Writer Solution - I [This solution has a hard to detect BUG!!!]

Reader Entry
P(mutex);
   if (wwc>0) or (wc>0) then begin 
            rwc++;
            V(mutex);
            P(rsem);
            P(mutex);
            rwc--;  end;
  rc++;
V(mutex);


Reader Exit
P(mutex);
  rc--;
  if (rc=0) and (wwc>0) then V(wsem);
V(mutex);

Writer Entry
P(mutex);
if (rc>0)or(wc>0)or(rwc>0)or(wwc >0)
         then begin
            wwc++;
            V(mutex);
            P(wsem);
            P(mutex);
            wwc--; end;
 wc++;
 V(mutex);

Writer Exit
  P(mutex);
   wc-- ;   
   if (rwc>0) then 
      for i:=1 to rwc do V(rsem)
   else if (wwc>0) then V(wsem);
  V(mutex)

 

Correct Reader Writer Solution

Reader Entry

P(mutex);
   if (wwc>0) or (wc>0) then begin 
            rwc++;
            V(mutex);
            P(rsem);
            rwc--; 
      end;
  rc++;
  if rwc>0 then V(rsem)
  else V(mutex);

Reader Exit

P(mutex);
  rc--;
  if (rc=0) and (wwc>0) then V(wsem);
  else V(mutex);

Writer Entry
P(mutex);
if (rc>0)or(wc>0)
         then begin
            wwc++;
            V(mutex);
            P(wsem);
            wwc--; 
         end;
    wc++;
 V(mutex);

Writer Exit
  P(mutex);
   wc-- ;   
   if (rwc>0) then V(rsem)
   else 
      if (wwc>0) then V(wsem);
      else V(mutex)

 

Dining Philosoper with Deadlock

Philosopher i:

Pickup:

P(chpstk[i]);
P(chpstk[(i+1) mod 5);



Putdown:

V(chpstk[i]);
V(chpstk[(i+1) mod 5);



Note:   LEFT = i; RIGHT = (i+1) mod 5

 

Dining Philosopher with no deadlock (but has starvation)

philosopher i:

Pickup: 
P(mutex)
while not(chpstk[LEFT]and chpstk[RIGHT])   
     do begin
        V(mutex);
        P(sleep[i]);
        P(mutex);
     end;
chpstk[LEFT]:=false; chpstk[RIGHT]:=false;
V(mutex);

PutDown
P(mutex)
   chpstk[LEFT]:=true;  
   chpstk[RIGHT]:=true;
   V(sleep[(i+4) mod 5]);
   V(sleep[RIGHT]);
V(mutex);