ada Implementing the producer-consumer pattern Producer-Consumer pattern using the Ada Rendezvous mechanism


Example

A synchronous producer-consumer solution ensures that the consumer reads every data item written by the producer exactly one time. Asynchronous solutions allow the consumer to sample the output of the producer. Either the consumer consumes the data faster than it is produced, or the consumer consumes the data slower than it is produced. Sampling allows the consumer to handle the currently available data. That data may be only a sampling of the data produced, or it may be already consumed data.

------------------------------------------------------------------
-- synchronous PC using Rendezvous --
------------------------------------------------------------------
with Ada.Text_IO; use Ada.Text_IO;

procedure PC_Rendezvous is
   task Producer;
   task Consumer is
      entry Buf(Item : in Integer);
   end Consumer;
   task body Producer is
   begin
      for I in 1..10 loop
         Put_Line("Producer writing" & Integer'Image(I));
         Consumer.Buf(I);
      end loop;
   end Producer;
   task body Consumer is
      Temp : Integer;
   begin
      loop
         select
            accept Buf(Item : in Integer) do
               temp := Item;
            end;
            Put_Line("Consumer read" & Integer'Image(Temp));
         or
            terminate;
         end select;
      end loop;
   end Consumer;

begin
   null;
end PC_Rendezvous;