Synchronization Example

 

 

(* This program should print out “the sum is 40”, but due to interference in the critical

section when updating the variable n, something less would sometimes be printed out

(i.e., 39, 27, 37, 20, etc.). *)

 

program increment_1;

const m = 20;

var n : integer;

procedure incr;

var i : integer;

begin

   for i := 1 to m do

   begin

       n := n + 1;

   end;

end;

begin (* main program executable code *)

   n := 0;

   cobegin

       incr; incr;

   coend;

   writeln (‘ the sum is ‘, n)

end.

 

 

(* This program uses semaphores to protect the critical section.  Each time this program

runs it would print out “the sum is 40”. *)

 

program increment_2;

const m = 20;

var   n : integer;

       s : semaphore;

procedure incr;

var i : integer;

begin

   for i := 1 to m do

       begin

          wait(s);

          n := n + 1;

          signal(s);

       end;

end;

begin (* main program executable code *)

   n := 0;

   s := 1;

   cobegin

       incr; incr;

   coend;

   writeln (‘ the sum is ‘, n)

end.