Channel Directions in Ada
Ada doesn’t have built-in channels like Go, so we’ll use Ada’s tasking system to simulate similar behavior. We’ll use protected objects to ensure thread-safe communication between tasks.
with Ada.Text_IO; use Ada.Text_IO;
procedure Channel_Directions is
protected type Message_Queue is
entry Send (Msg : in String);
entry Receive (Msg : out String);
private
Message : String (1 .. 100);
Is_Empty : Boolean := True;
end Message_Queue;
protected body Message_Queue is
entry Send (Msg : in String) when Is_Empty is
begin
Message (1 .. Msg'Length) := Msg;
Is_Empty := False;
end Send;
entry Receive (Msg : out String) when not Is_Empty is
begin
Msg := Message (1 .. Message'Length);
Is_Empty := True;
end Receive;
end Message_Queue;
Pings : Message_Queue;
Pongs : Message_Queue;
task Ping;
task Pong;
task body Ping is
begin
Pings.Send ("passed message");
end Ping;
task body Pong is
Msg : String (1 .. 100);
begin
Pings.Receive (Msg);
Pongs.Send (Msg);
end Pong;
begin
delay 0.1; -- Give tasks time to complete
declare
Result : String (1 .. 100);
begin
Pongs.Receive (Result);
Put_Line (Result);
end;
end Channel_Directions;
This Ada program demonstrates a concept similar to channel directions using Ada’s tasking system:
We define a protected type
Message_Queue
that acts like a channel, withSend
andReceive
entries.The
Ping
task sends a message to thePings
queue.The
Pong
task receives a message fromPings
and sends it toPongs
.In the main procedure, we wait a short time for the tasks to complete, then receive and print the message from
Pongs
.
To run this program, save it as channel_directions.adb
and compile it with an Ada compiler:
$ gnatmake channel_directions.adb
$ ./channel_directions
passed message
This example demonstrates how Ada’s tasking system can be used to achieve similar functionality to Go’s channel directions. While the syntax and concepts are different, the core idea of safe, directional communication between concurrent processes is preserved.