int nr := 0, nw := 0, dr := 0, dw := 0 sem mutex := 1, r := 0, w := 0
readEnter() { P(mutex);
// need mutual exclusion
// writer is in, better block
// increment number of delayed readers // release mutual exclusion
// block on read semaphore
}
if (nw > 0) { dr++;
}
V(mutex); P(r);
}
nr++;
if (dr > 0) {
dr−−; V(r);
// going to go in, record this
// other delayed readers, let them in
// one fewer delayed reader // actually let reader in
// no readers waiting, release mutex
else V(mutex);
readExit() { P(mutex);
// need mutual exclusion nr−−; // one reader is out
if (nr == 0 and dw > 0) { // last reader and writer waiting, so let it in
dw−−; V(w);
else V(mutex);
writeEnter() { P(mutex);
// one fewer delayed writer // actually let writer in
// release mutual exclusion
}
}
}
// need mutual exclusion
if (nr > 0 or nw > 0) { // someone else is in, better block
}
nw++; V(mutex);
writeExit() { P(mutex);
}
dw++; V(mutex); P(w);
// increment number of delayed writers // release mutual exclusion
// block on write semaphore
// going to go in, record this
// release mutual exclusion
// need mutual exclusion // one fewer writer in
nw−−;
if (dr > 0)
// reader waiting, let it in
// decrement and let in reader
// writer waiting, let it in
// decrement and let writer in
// release mutual exclusion
1
dr−−; V(r); else if (dw > 0)
dw−−; V(w); else V(mutex);