Channels: Many senders
● Advanced3 min
Several tasks can put into one channel; close it once all of them are done.
fn main() ! Error {
const (send, receive) = Channel<Int>(capacity: 8)
const a = spawn {
for n in 0..3 {
send.put(n)
}
}
const b = spawn {
for n in 10..13 {
send.put(n)
}
}
const _closer = spawn {
try a.wait()
try b.wait()
send.close()
}
let total = 0
for n in receive {
total += n
}
print(total)
}The program ran and printed:
kavach run workers.kav
36A third task waits for both senders, then closes the channel, so the loop that takes knows when to stop.