1with Ada.Text_IO; use Ada.Text_IO;
2
3package body Bounded_Buffer is
4
5 type Item_Array is array (Positive range <>) of Item_Type;
6
7 protected type Buffer (Capacity : Positive) is
8 entry Put (Item : in Item_Type);
9 entry Get (Item : out Item_Type);
10 function Count return Natural;
11 function Is_Full return Boolean;
12 function Is_Empty return Boolean;
13 private
14 Store : Item_Array (1 .. Capacity);
15 Head : Positive := 1;
16 Tail : Positive := 1;
17 Size : Natural := 0;
18 end Buffer;
19
20 protected body Buffer is
21
22 entry Put (Item : in Item_Type)
23 when Size < Capacity is
24 begin
25 Store (Tail) := Item;
26 Tail := (Tail mod Capacity) + 1;
27 Size := Size + 1;
28 end Put;
29
30 entry Get (Item : out Item_Type)
31 when Size > 0 is
32 begin
33 Item := Store (Head);
34 Head := (Head mod Capacity) + 1;
35 Size := Size - 1;
36 end Get;
37
38 function Count return Natural is
39 begin
40 return Size;
41 end Count;
42
43 function Is_Full return Boolean is
44 begin
45 return Size = Capacity;
46 end Is_Full;
47
48 function Is_Empty return Boolean is
49 begin
50 return Size = 0;
51 end Is_Empty;
52
53 end Buffer;
54
55 task type Producer (Buf : access Buffer; Id : Positive);
56 task type Consumer (Buf : access Buffer; Id : Positive);
57
58 task body Producer is
59 Value : Item_Type;
60 begin
61 for I in 1 .. 10 loop
62 Value := Item_Type'Val (I + Id * 100);
63 Buf.Put (Value);
64 Put_Line ("Producer" & Id'Image &
65 " put item" & I'Image);
66 end loop;
67 end Producer;
68
69 task body Consumer is
70 Value : Item_Type;
71 begin
72 for I in 1 .. 10 loop
73 Buf.Get (Value);
74 Put_Line ("Consumer" & Id'Image &
75 " got item" & I'Image);
76 end loop;
77 end Consumer;
78
79end Bounded_Buffer;