Example: Bounded Buffers implemented using Monitors

 

Monitor BoundedBuffer;

 

var

 Buffer:array[0..NumElts-1]of ElementType;

 get,put,count:Integer;

 NotFull,NotEmpty:Condition;

  (* NotFull: Signaled when count<NumElts *)

  (* NotEmpty: Signaled when count>0      *)

 

Procedure Entry Insert(Data:ElementType);     Process Producer;

begin                                        var

 While count=n do                       Data:ElementType;

  NotFull.wait;                          BB:BoundedBuffer;

 Buffer[put]:=Data;                     begin

 put:=(put+1)mod NumElts;                 While True do begin

 count:=count+1;                           Produce(Data);

 NotEmpty.signal;                          BB.Insert(Data);

end;                                    end;

                                        end.

Procedure Entry Remove(var Data:ElementType);

begin                                   Process Consumer;

 while count=0 do                       var

  NotEmpty.wait;                         Data:ElementType;

 Data:=Buffer[get];                     BB:BoundedBuffer;

 get:=(get+1)mod NumElts;                 begin

 count:=count-1;                        While True do begin

 NotFull.signal;                          BB.Remove(Data);

end;                                      Consume(Data);

                                         end;

begin (* Init Code *)                  end.

 get:=0; put:=0; count:=0;

end;