foil for Section 12.2.8 monitor for readers and writers
read-write: monitor
entry-procedures startread, endread, startwrite, endwrite
var ar : integer % we now need to know if there are active readers
busy-writing : boolean;
free-to-read, free-to-write : condition;
% in startread a reader now waits for a writing writer tofinish
procedure startread ()
begin ar := ar +1;
if busy-writing then WAIT (free-to-read);
SIGNAL (free-to-read) % If one reader can read, all can read. Each
end startread; % reader wakes up another until none is left.
% in endread the last reader signals a writer
procedure endread ()
begin ar := ar-1;
if ar = 0 then SIGNAL(free-to-write)
end endread;
% in startwrite a writer now waits for a writing writer to finish
%or for no waiting readers
procedure startwrite ()
begin if busy-writing or ar > 0 then WAIT (free-to-write);
busy-writing := true
end startwrite;
% in endwrite any waiting reader is now given priority
over any waiting writer
procedure endwrite ()
begin busy-writing := false;
if ar>0 then SIGNAL(free-to-read)
else SIGNAL (free-to-write)
end endwrite;
end read-write;