The Readers and Writers Problem.

(Concurrent readers OR exclusive Writer).

All readers execute reader-entry at start and reader-exit on end of reading zone. Similar for writers. Mutex semaphores are initialized to 1 and others (rsem, wsem) are initialized to 0. the variables rc, wc, rwc and wwc are counters (reader count, reader waiting count etc) and a inited to 0.

PROGRAM 1:   Has writer starvation.

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);

PROGRAM 2: Has reader 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);

PROGRAM 3: Correct Solution - version A

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);

RW3

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)

PROGRAM 4: Correct Solution - version B

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);                         RW4

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)