Channels
Channels are the communication mean that can be used for passing data from one piece of code to another. The great thing about channels is that they are thread-compatible, thus it is possible for different threads to talk to each other. In this section, we will learn how to use channels in Perl 6.
Basic use cases
Channels are defined by the Channel
class. To create a new channel variable, call the constructor:
my $channel = Channel.new;
Now, we can send data to the channel using the send
method and receive it with the receive
method:
my $channel = Channel.new; $channel.send(42); my $value = $channel.receive(); say $value;
This program does a trivial thing—it sends the value to the channel and reads it immediately. The program prints the value of 42
, which went through the channel.
Now, let us modify the program and introduce a second thread in it so that the channel is populated in that thread and the result is read in the main program:
my $channel = Channel.new(); start { $channel...