(40 points)
A bounded semaphore s is a counting semaphore that cannot exceed
a given value smax > 0. The corresponding up and
down operations are:
up(s): wait until s < smax; then increment s by 1
down(s): wait until s > 0; then decrement s by 1
Write a monitor to implement bounded semaphores. (Hint: assume the
semaphore is to be initialized to the constant SINIT and the maximum
value is SMAX.)
Answer:
type boundedsem = monitor
(* scount is the integer value of the
semaphore; if this is too big and the
process tries to up it, the process
will block on toobig; similarly, if the
value is too small and the process tries
to down it, the process will block on
toosmall. ` *)
var scount : integer;
toobig, toosmall : condition;
(* straighforward implementation of up *)
procedure entry up;
begin
(* if too big, wait until ok *)
while scount >= SMAX do
toobig.wait;
(* increment and notify someone
waiting for the semaphore to be
nonzero that it is *)
scount := scount + 1;
toosmall.signal;
end;
(* straighforward implementation of down *)
procedure entry down;
begin
(* if too small, wait until ok *)
while scount <= 0 do
toosmall.wait;
(* decrement and notify someone
waiting for the semaphore to be
less than SMAX that it is *)
scount := scount - 1;
toobig.signal;
end;
begin (* initialization *)
scount := SINIT;
end.