Lyricdev
GitHub

class Channel

pub class Channel<T>

A queue of values between tasks: values go in with Channel.send and come out with Channel.recv, in the order they went in.

Unbuffered — a capacity of 0 — a send waits until a receiver takes the value; buffered, it waits only while the buffer is full. Channel.close ends it: what is buffered can still be received, then recv answers null; a send throws ChannelClosed. It works within a thread and across threads: a send happens before the receive that gets its value.

The guard holds while the channel's state changes, and never while anything waits or a body runs. The locks of this module are taken in one order — channels by their ids, then a task's guard or a scheduler's inbox — so no two threads wait on each other's.

Methods

pub static fn new(capacity: int = 0): Channel<T>

Creates a channel that holds up to capacity values no task has received yet.

A capacity of 0 — the default — holds none: a send meets a receive. A negative capacity counts as 0.

pub mut fn send(value: T): void throws [ChannelClosed, Cancelled]

Puts value into the channel: to a task waiting to receive, or into the buffer while there is room — else the running task waits until a receiver takes it.

Errors

Throws ChannelClosed on a closed channel, and when the channel closes while it waits; Cancelled in a cancelled task.

pub mut fn recv(): ?T throws Cancelled

Returns the next value of the channel: from the buffer, or from a task waiting to send — else the running task waits for one. Returns null once the channel is closed and empty.

Errors

Throws Cancelled in a cancelled task.

pub mut fn close(): void

Closes the channel: the tasks waiting to receive get null, those waiting to send throw ChannelClosed; what is buffered can still be received. Closing a closed channel does nothing.