std::channels
Channels: typed queues between tasks, each split into a Sender and a
Receiver. Channel.buffered(capacity) lets a producer run ahead of
its consumer; Channel.unbuffered() makes every send wait for a
receive. Sender.send returns Err once the channel is closed,
Sender.close closes it, and Receiver.receive returns None when it
is closed and drained. Channel.select waits on several channel
operations and timers at once, and Receiver.receive_within on one
channel with a timeout. How a task waiting on a channel is cancelled is a
language rule (Concurrency).
Import with import std::channels.
Exports
Section titled “Exports”Multiplexing
Section titled “Multiplexing”Producers that share one message type fan in through a single channel of an enum:
concurrent events: Channel<Event> = Channel.buffered(2) p1 = Task.spawn(fn -> Sender.send(events.sender, Event.UserMsg("hello"))) p2 = Task.spawn(fn -> Sender.send(events.sender, Event.Tick(1))) case Receiver.receive(events.receiver) Some(.UserMsg(msg)) -> handle_msg(msg) Some(.Tick(n)) -> handle_tick(n) Some(.Shutdown) -> io.print("shutting down") None -> io.print("channel closed") end _ = Task.await(p1) _ = Task.await(p2) Ok(Unit) end
The enum is the multiplexing mechanism: producers tag their messages, and the consumer pattern matches on variants.
Channel.select covers what one channel cannot: a timeout, a send that
must not block, and channels of different element types or owned by
different code. Each arm’s handler maps its own outcome to the result:
answer = Channel.select([ Arm.receive(replies, fn reply -> Maybe.with_default(reply, "closed")), Arm.receive(errors, fn error -> "failed: ${Maybe.with_default(error, 0)}"), Arm.after(Duration.seconds(5), fn -> "timed out"), ])
struct Channel
Section titled “struct Channel”struct Channel<T> sender: Sender<T> receiver: Receiver<T> end
Typed FIFO channel for communication between tasks, held as its two
halves. Producers Sender.send values; consumers Receiver.receive them
in arrival order.
The halves are what you pass around. A worker that reads its inbox
takes a Receiver<T> and cannot send on it; the callers hold the
Sender<T> and cannot read what they wrote. Handing over a whole
Channel<T> hands over both, which is right for the code that
created it and rarely right for anything downstream.
A channel is either buffered or not. Channel.buffered lets a producer
run ahead by up to capacity values, while Channel.unbuffered makes
every send wait for a paired receive. There is no Channel.new,
since a channel is one or the other.
A channel outlives the concurrent block that made it: it can be
returned out of one block and read in a later one. It is freed when
nothing refers to it.
Channel.buffered
Section titled “Channel.buffered”fn buffered<T>(capacity: PositiveInt) -> Channel<T>
type function on Channel
Construct a Channel<T> that buffers up to capacity pending values, so a
producer can run that far ahead of its consumer before send blocks.
capacity is a PositiveInt. A channel with no buffer is made by
Channel.unbuffered, so Channel.buffered<Int>(0) is an error when
the program is compiled.
ch = Channel.buffered<Int>(1)
assert Ok(_) = Sender.send(ch.sender, 7)
assert Receiver.receive(ch.receiver) == Maybe.Some(7)
Channel.unbuffered
Section titled “Channel.unbuffered”fn unbuffered<T>() -> Channel<T>
type function on Channel
Construct a Channel<T> with no buffer, where every send waits for a
paired receive and every receive for a send.
A send does not return until a receiver takes the value. That makes
it a poor fit for reporting work nobody is waiting on, and a task
that sends and then receives on the same channel deadlocks. Under
clock Clock.Virtual that deadlock is reported; on the system clock
the task hangs.
ch = Channel.unbuffered<Int>()
sent = concurrent
w = Task.spawn(fn -> Sender.send(ch.sender, 7))
got = Receiver.receive(ch.receiver)
_ = Task.await(w)
got
end
assert sent == Maybe.Some(7)
Channel.select
Section titled “Channel.select”fn select<R>(arms: NonEmptyList<Arm<R>>) -> R
type function on Channel
Wait until one of arms can finish, run that arm’s handler, and
return what it returns. An arm is a receive (Arm.receive), a send
(Arm.send) or a timer (Arm.after), and the arms may be on channels
of different element types, since each handler turns its own outcome
into the one result type R.
When several arms can finish as select starts, the first one listed
wins, so a run repeats exactly. That is a bias: an arm listed first
that is always ready keeps the others waiting. A loop that must serve
several busy channels fairly rotates its arms each round. Once
select is waiting, the first arm to become ready wins.
A receive on a closed channel is ready at once with None, and a send
on one is ready at once with Err(ChannelClosed), so a select whose
channels are all closed runs its first listed channel arm. A timer
counts on the clock in force: under clock Clock.Virtual it fires as
soon as every task is waiting, without a real wait. A timer of zero
or less is ready at once, so Arm.after of zero listed last makes a
select that never waits. The arms are a NonEmptyList, which a
list literal of arms is; a list built while the program runs goes
through NonEmptyList.try_from.
Waiting is cancellable, as Receiver.receive is: when the enclosing
concurrent block’s context fires, the wait ends and no handler runs.
ch = Channel.buffered<Int>(1)
assert Ok(_) = Sender.send(ch.sender, 7)
got = Channel.select([
Arm.receive(ch.receiver, fn n -> Maybe.with_default(n, 0)),
Arm.after(Duration.seconds(1), fn -> -1),
])
assert got == 7
Channel.inspect
Section titled “Channel.inspect”impl Debug for Channel<T>
fn inspect<T>(value: Channel<T>) -> String where T: Debug
impl Debug.inspect
type Sender
Section titled “type Sender”type Sender<T>
The writing half of a Channel<T>, and the half that can close it.
Closing says that nothing more is coming, which is the producer’s to
say. A Receiver has no close, so a consumer cannot end the channel
for the tasks still writing to it.
Sender.send
Section titled “Sender.send”fn send<T>(sender: Sender<T>, value: T) -> Result<Unit, ChannelClosed>
type function on Sender
Send a value on the channel. Blocks until the value is taken (for
unbuffered channels) or capacity is available (for buffered). Returns
Err(ChannelClosed) if the channel was closed at send time, or closes
while the send waits. Waiting is cancellable: when the enclosing
concurrent block’s context fires (a deadline, or a cancellation
from above), the wait ends and the task unwinds there.
ch = Channel.buffered<Int>(1)
assert Ok(_) = Sender.send(ch.sender, 7)
Sender.close
Section titled “Sender.close”fn close<T>(sender: Sender<T>) -> Unit
type function on Sender
Close the channel. Subsequent send calls return Err(ChannelClosed),
and so do sends waiting for room when it closes. Values already
buffered are still delivered to receive. Closing a closed channel
does nothing.
ch = Channel.buffered<Int>(1)
Sender.close(ch.sender)
Sender.close(ch.sender)
assert Receiver.receive(ch.receiver) == Maybe.None
assert Sender.send(ch.sender, 7) == Result.Err(ChannelClosed)
Sender.close_on_drain
Section titled “Sender.close_on_drain”fn close_on_drain<T>(sender: Sender<T>) -> Unit
type function on Sender
Close the channel when the program starts shutting down, as its
supervisors begin to drain. A task that reads the channel until it
closes then finishes what is queued and ends, so the drain does not
wait out its grace period for a reader parked on an empty channel.
A close before shutdown cancels it, and a close after shutdown
closed the channel does nothing.
ch = Channel.buffered<Int>(1)
Sender.close_on_drain(ch.sender)
assert Ok(_) = Sender.send(ch.sender, 1)
Sender.close(ch.sender)
assert Receiver.receive(ch.receiver) == Maybe.Some(1)
Sender.inspect
Section titled “Sender.inspect”impl Debug for Sender<T>
fn inspect<T>(value: Sender<T>) -> String where T: Debug
impl Debug.inspect
type Receiver
Section titled “type Receiver”type Receiver<T>
The reading half of a Channel<T>. A consumer holding one can receive
from the channel, and can neither write to it nor close it.
Receiver.receive
Section titled “Receiver.receive”fn receive<T>(receiver: Receiver<T>) -> Maybe<T>
type function on Receiver
Receive the next value from the channel. Blocks until a value arrives,
the channel is closed and drained (returns None), or the enclosing
concurrent block’s context fires (the task unwinds there). After
close, the values still buffered are delivered to the next receive
calls, and every call after them returns None.
ch = Channel.buffered<Int>(1)
assert Ok(_) = Sender.send(ch.sender, 7)
assert Receiver.receive(ch.receiver) == Maybe.Some(7)
Receiver.receive_within
Section titled “Receiver.receive_within”fn receive_within<T>(receiver: Receiver<T>, wait: Duration) -> Result<Maybe<T>, TimedOut>
type function on Receiver
Receive the next value, waiting at most wait. Ok(Some(value)) is a
value, Ok(None) a channel closed and drained, and Err(TimedOut) a
wait that ran out first, on the clock in force. A value already
waiting is received even when wait is zero. A wait past about 292
years, the longest the clock counts, waits that long, so it never
runs out.
For waiting on more than one channel, or on a send, use
Channel.select.
ch = Channel.buffered<Int>(1)
assert Receiver.receive_within(ch.receiver, Duration.seconds(0)) == Result.Err(TimedOut)
assert Ok(_) = Sender.send(ch.sender, 7)
assert Receiver.receive_within(ch.receiver, Duration.seconds(1)) == Result.Ok(Maybe.Some(7))
Receiver.inspect
Section titled “Receiver.inspect”impl Debug for Receiver<T>
fn inspect<T>(value: Receiver<T>) -> String where T: Debug
impl Debug.inspect
type Arm
Section titled “type Arm”type Arm<R>
One way a Channel.select can finish, with the handler that turns its
outcome into the select’s result. Build one with Arm.receive,
Arm.send or Arm.after.
Arm.receive
Section titled “Arm.receive”fn receive<T, R>(receiver: Receiver<T>, handle: (Maybe<T>) -> R) -> Arm<R>
type function on Arm
An arm that finishes when receiver has a value, or is closed and
drained, and passes handle the value or None.
ch = Channel.buffered<Int>(1)
Sender.close(ch.sender)
assert Channel.select([Arm.receive(ch.receiver, fn n -> n)]) == Maybe.None
Arm.send
Section titled “Arm.send”fn send<T, R>(sender: Sender<T>, value: T, handle: (Result<Unit, ChannelClosed>) -> R) -> Arm<R>
type function on Arm
An arm that finishes when value can be sent on sender, and passes
handle the send’s result: Ok(Unit), or Err(ChannelClosed) when
the channel is closed.
ch = Channel.buffered<Int>(1)
sent = Channel.select([Arm.send(ch.sender, 7, fn r -> r == Result.Ok(Unit))])
assert sent
assert Receiver.receive(ch.receiver) == Maybe.Some(7)
Arm.after
Section titled “Arm.after”fn after<R>(wait: Duration, handle: () -> R) -> Arm<R>
type function on Arm
An arm that finishes once wait has passed on the clock in force,
counted from the start of the select, and runs handle. A zero or
negative wait is ready at once. A wait past about 292 years, the
longest the clock counts, waits that long, so the arm never finishes.
ch = Channel.buffered<Int>(1)
got = Channel.select([
Arm.receive(ch.receiver, fn _ -> "a value"),
Arm.after(Duration.seconds(0), fn -> "nothing yet"),
])
assert got == "nothing yet"
Arm.inspect
Section titled “Arm.inspect”impl Debug for Arm<R>
fn inspect<R>(value: Arm<R>) -> String where R: Debug
impl Debug.inspect
type ChannelClosed
Section titled “type ChannelClosed”type ChannelClosed
Returned by Sender.send when the channel was closed at the time
the send attempted to enqueue, or closed while the send waited.
ChannelClosed.inspect
Section titled “ChannelClosed.inspect”impl Debug for ChannelClosed
fn inspect(value: ChannelClosed) -> String
impl Debug.inspect
type TimedOut
Section titled “type TimedOut”type TimedOut
Returned by Receiver.receive_within when its wait ran out before a
value arrived or the channel closed.
TimedOut.inspect
Section titled “TimedOut.inspect”impl Debug for TimedOut
fn inspect(value: TimedOut) -> String
impl Debug.inspect