Corso di Raku / Programmazione funzionale, concorrente, reattiva e web / Programmazione concorrente / Channel / Exercises / Sommate un channel
Soluzione: Sommate un channel
Ecco una possibile soluzione del compito.
Codice
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;🦋 Trova il programma nel file channel-sum.raku.
Output
21Commenti
La promise del produttore invia i sei valori su un thread e chiude il channel. La promise del consumatore, su un altro thread, usa
.listper raccogliere tutto fino alla chiusura e ne restituisce la somma ([+]somma1 + 2 + … + 6).await $producer, $consumeraspetta entrambe le promise e restituisce i loro risultati in ordine. Il risultato del produttore qui non serve ($sent); quello del consumatore è la somma,21. È il channel a portare in sicurezza i valori dal thread produttore al thread consumatore.