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

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