Course of Raku / Functional, concurrent, reactive, and web programming / Concurrent programming / Channels / Exercises / Sum a channel
Solution: Sum a channel
Here is a possible solution to the task.
Code
my $c = Channel.new;
my $producer = start {
$c.send($_) for 1..6;
$c.close;
};
my $consumer = start {
[+] $c.list;
};
my ($sent, $sum) = await $producer, $consumer;
say $sum;🦋 You can find the source code in the file channel-sum.raku.
Output
21Comments
The producer promise sends the six values on one thread and closes the channel. The consumer promise, on another thread, uses
.listto collect everything up to the close and returns the sum ([+]adds1 + 2 + … + 6).await $producer, $consumerwaits for both promises and returns their results in order. The producer’s result is not needed here ($sent); the consumer’s is the sum,21. The channel is what safely carries the values from the producer thread to the consumer thread.
Course navigation
← Sum a channel | Drain a channel →