home *** CD-ROM | disk | FTP | other *** search
/ cs.rhul.ac.uk / www.cs.rhul.ac.uk.zip / www.cs.rhul.ac.uk / pub / CS375 / pcmon2.pfc < prev    next >
Text File  |  1999-03-15  |  1KB  |  75 lines

  1. program pcmon2;
  2.  
  3. (* producer-consumer problem  - correct 
  4. monitor solution 
  5.  
  6. file is ~simon/teaching/CS375/mutex/pcmon2.pfc *)
  7.  
  8. monitor buffer;
  9. export
  10.   put, take;
  11. const
  12.   buffmax = 4;
  13. var
  14.   store: array[0..buffmax] of char;
  15.   count: integer;
  16.   notfull, notempty: condition;
  17.   nextin, nextout: integer;
  18.  
  19. procedure put(ch: char);
  20. begin
  21.   if count > buffmax then
  22.     delay(notfull);
  23.   store[nextin] := ch;
  24.   count := count + 1;
  25.   nextin := (nextin + 1) mod (buffmax + 1);
  26.   resume(notempty)
  27. end;  (* put *)
  28.  
  29.  
  30. procedure take(var ch: char);
  31. begin
  32.   if count = 0 then
  33.     delay(notempty);
  34.   ch := store[nextout];
  35.   count := count - 1;
  36.   nextout := (nextout + 1) mod (buffmax + 1);
  37.   resume(notfull)
  38. end;  (* take *)
  39.  
  40.  
  41.  
  42. begin  (* body of buffer *)
  43.   count := 0;
  44.   nextin := 0;
  45.   nextout := 0
  46. end;  (* buffer *)
  47.  
  48.  
  49. process producer;
  50. var
  51.   local: char;
  52. begin
  53.   for local := 'a' to 'z' do
  54.     buffer.put(local);
  55. end;  (* producer *)
  56.  
  57.  
  58. process consumer;
  59. var
  60.   ch: char;
  61. begin
  62.   repeat
  63.     buffer.take(ch);
  64.     write(ch)
  65.   until ch = 'z';
  66.   writeln
  67. end;  (* consumer *)
  68.  
  69. begin  (* main *)
  70.   cobegin
  71.     producer;
  72.     consumer
  73.   coend
  74. end.
  75.