The following is a Pascal-like program a producer/consumer implementation where semaphores wait and signals are used to implement monitor wait and signals.  Note that the semaphore s performs functions like the monitor entry queue.  The semaphores full and empty perform conditionvariable functions.

 

1.  wait(s) is placed at the beginning and end of each monitor procedure

 

2.  The monitor wait(conditionvariable) is replaced by:

 

condcount := condcount + 1;

signal(s);

wait(condsem);

condcount := condcount – 1;

 

3.  The monotor signal(conditionvar) is replaced by:

 

if condcount > 0 then signal(condsem) else signal(s);

 

***************************************

program prod_cons_sem-mon;

const sizeofbuffer = 20

var b: array[0..sizeofbuffer] of integer;

      in, out, n, empty_count, full_count: integer

      s, empty, full: semaphore

procedure append(x: integer);

begin

   wait(s);

   if n=sizeofbuffer+1 then

      begin

      full_count := full_count + 1;

      wait(full);

      full_count := full_count – 1;

      end;

   code to place item x  in buffer;

   if empty_count > 0 then signal(empty) else signal(s);

end;

procedure remove (var y: integer);

begin

   wait(s);

   if n=0 then

      begin

      empty_count := empty_count + 1;

      signal(s);

      wait(empty);

      empty_count := empty_count – 1;

      end;

   code to remove item from buffer and store it in y;

   if full_count > 0 then signal(full) else signal (s);

end;

procedure producer(x);

repeat

   produce item x;

   append(x);

until forever;

procedure consumer(y)

repeat

   remove(y);

   consume item y;

until forever;

begin (* main program *);

   n := 0; full_count := 0; empty_count := 0; s := 1; empty := 0; full := 0;

   cobegin

      producer; consumer;

   coend

end.