Channel
class Channel<T> Import
Source: use task::{Channel}; compiler/src/prelude/task.hy A bounded queue for passing values between tasks.
send waits while the channel is full and recv while it is empty, so a
channel also paces producers and consumers. Values are shared, not copied
(tasks share the heap). For OS threads, use thread::channel.
Methods#
| Name | Description |
|---|---|
send | Adds value to the channel, waiting while it is full (a suspension point). |
try_send | Adds value if there is room, without waiting. |
recv | Takes the oldest value, waiting while the channel is empty (a suspension point). |
try_recv | Takes the oldest value if there is one, without waiting. |
close | Closes the channel: no more values can be sent. |
len | Returns the number of values waiting to be received. |
capacity | Returns the most values the channel can hold. |
is_closed | Returns true once close has been called. |
Examples#
use task::{scope, channel, Scope, Channel};
use tests::assert;
let sum = scope(fn (Scope s) {
let ch: Channel<int> = channel(2);
let producer = s.spawn(fn () use (ch) {
let i = 1;
while i <= 5 {
ch.send(i) ?? ();
i = i + 1;
}
ch.close();
});
let total = 0;
while let Result::Ok(v) = ch.recv() {
total = total + v;
}
producer.join() ?? ();
return total;
});
assert!((sum ?? 0) == 15);
See also#
Channel::sendChannel::recvthread::channelScope: A runningscope, used to start child tasks withspawn.Task: A handle to a child task started withScope::spawn.