Channels in Chapel
use Time;
proc main() {
// Create a new channel using a sync variable
var messages: sync string;
// Start a new task to send a message
begin {
messages.writeEF("ping");
}
// Receive the message from the channel
var msg = messages.readFE();
writeln(msg);
}
Channels in Chapel are implemented using sync variables. These variables provide a way for tasks to communicate and synchronize with each other.
In this example, we create a sync string
variable called messages
. This acts as our channel for passing string messages between tasks.
To send a value into the channel, we use the writeEF
method (write “empty to full”). This is done in a new task started with the begin
keyword, which is Chapel’s equivalent to goroutines.
begin {
messages.writeEF("ping");
}
To receive a value from the channel, we use the readFE
method (read “full to empty”). This operation blocks until a value is available, similar to receiving from a channel.
var msg = messages.readFE();
writeln(msg);
When we run the program, the “ping” message is successfully passed from one task to another via our sync variable.
$ chpl channels.chpl
$ ./channels
ping
By default, writeEF
and readFE
operations on sync variables block until the variable is in the appropriate state. This property allows us to synchronize tasks without needing additional synchronization mechanisms.
In Chapel, sync variables provide a powerful way to implement channel-like behavior, allowing for communication and synchronization between concurrent tasks.