Simple Monitor

 

program example;

   monitor resource_allocator;

   var   busy: boolean;

          mon_queue: condition_variable;

 

(* monitor procedures get_resource and return resource are printed side-by-side to

conserve space *)

 

   procedure get_resource;                     procedure return_resource;      

       begin                                               begin

          if busy then wait(mon_queue);            busy := false;

          busy := true;                                    signal(mon_queue);

       end;                                                 end;

  

   begin (* monitor executable code *)

      busy := false;

   end;

 

(* The monitor ends here.  The code below belongs to the main program not the

monitor. *)

 

procedure user;

   begin

       while(true) do

          begin

              resource_allocator.get_resource;

                 critical section

              resource_allocator.return_resource;

          end;

   end;

 

(* The calls to user inside cobegin and coend invoke four threads of the user code all

competing with each other for repeated access to the critical section. *)

 

cobegin

   user; user; user; user;

coend.