Skip to content
CryoCryo home
Stdlibsync

channel

import std::sync::channel; · source

Multi-producer, single-consumer channels. Channel::unbounded::<T>() and Channel::bounded::<T>(capacity) open a channel and return both of its ends together, its Sender<T> first. Each Sender<T> is independently owned and movable into its own thread, and is cloned for more producers. Values of any type — including owned data like String — move through the FIFO queue.

import std::core::pair::{ Pair };
import std::sync::channel::{ Channel, Receiver, Sender };
import std::thread;

const { first: tx, second: rx }: Pair<Sender<i32>, Receiver<i32>> = Channel::unbounded::<i32>();
// move `tx` into a worker thread; keep `rx` here
const h = thread::spawn(move () -> i32 {
    tx.send(42);
    return 0;       // `tx` is released with the closure as the thread ends
});
match (rx.receive()) {
    Result::Ok(v)  => { /* v is 42 */ }
    Result::Err(_) => { }
}
h.join().unwrap();

Types

Channel

type struct Channel {}

An unbounded channel queues every value sent. A bounded one holds at most capacity values (at least 1): send on a full channel blocks until the receiver takes one, or returns the value in Err(SendError) if the receiver is dropped meanwhile.

Static functions

static unbounded<T>() -> Pair<Sender<T>, Receiver<T>>;

A channel that queues every value sent.

static bounded<T>(capacity: i64) -> Pair<Sender<T>, Receiver<T>>;

A channel holding at most capacity values: send on a full one waits for the receiver to take a value. Panics when capacity is less than 1.

Sender<T>

type struct Sender<T> {
    private inner: mut ChannelInner<T>*;
}

send moves a value into the queue, waiting for room on a full bounded channel. try_send never waits: on a full channel it hands the value back in Err(TrySendError::Full). clone() mints another producer; close() consumes the sender and is equivalent to dropping it early.

Methods

send(&this, value: T) -> Result<(), SendError<T>>;

Enqueue value, first waiting for room when a bounded channel is full. Returns Err(SendError{value}) if the receiver has been dropped (the value is handed back unconsumed).

try_send(&this, value: T) -> Result<(), TrySendError<T>>;

Enqueue value without waiting. Returns Err(Full(value)) when a bounded channel already holds its capacity (or no memory could be had for the value), Err(Disconnected(value)) when the receiver has been dropped; either hands the value back unconsumed.

clone(&this) -> Sender<T>;

Create another sender on the same channel (multi-producer).

close(mut this) -> void;

Explicitly drop this sender now (rather than at scope end). Useful after moving a sender into a thread body, where the value must be released before the body returns.

Receiver<T>

type struct Receiver<T> {
    private inner: mut ChannelInner<T>*;
}

receive() blocks; receive_timeout(duration) gives up with Err(Timeout) when the time runs out; try_receive() returns Err(Empty) immediately when nothing is queued. The receiver is not cloneable — there is one consumer.

A Receiver<T> is an Iterator<T>: for (value in rx) takes each value as it arrives and ends once every sender has dropped and the queue is drained.

import std::core::pair::{ Pair };
import std::sync::channel::{ Channel, Receiver, Sender };
import std::thread;

const { first: jobs, second: results }: Pair<Sender<i32>, Receiver<i32>> = Channel::bounded::<i32>(2);
const producer = thread::spawn(move () -> i32 {
    mut i: i32 = 0;
    while (i < 5) {
        jobs.send(i);
        i = i + 1;
    }
    return 0;
});
mut sum: i32 = 0;
for (value in results) {
    sum = sum + value;
}
producer.join().unwrap();

Methods

receive(&this) -> Result<T, ReceiveError>;

Block until a value is available and return it, or return Err(Disconnected) once every sender has dropped and the queue is drained.

receive_timeout(&this, duration: Duration) -> Result<T, ReceiveTimeoutError>;

Wait no longer than duration for a value and return it. Err(Timeout) when the time runs out first, Err(Disconnected) once every sender has dropped and the queue is drained.

try_receive(&this) -> Result<T, TryReceiveError>;

Non-blocking receive. Returns Err(Empty) if no value is ready but senders remain, Err(Disconnected) if the channel is drained and all senders have dropped.

The errors

type struct SendError<T> {
    value: T;
}
type enum TrySendError<T> {
    Full(T);
    Disconnected(T);
}
type enum ReceiveError with [Eq, Clone, Debug] {
    Disconnected;
}
type enum TryReceiveError with [Eq, Clone, Debug] {
    Empty;
    Disconnected;
}
type enum ReceiveTimeoutError with [Eq, Clone, Debug] {
    Timeout;
    Disconnected;
}

SendError

Properties
PropertyType
valueT

TrySendError

Variants
VariantNotes
Full(T)The channel already holds as many values as it can, or no memory could be had for one more.
Disconnected(T)The receiver has been dropped.

ReceiveError

Variants
Variant
Disconnected

TryReceiveError

Variants
Variant
Empty
Disconnected

ReceiveTimeoutError

Variants
VariantNotes
TimeoutThe time ran out with no value sent and a sender still alive.
DisconnectedEvery sender has dropped and the queue is empty.

Disconnection

When every Sender has been dropped, a blocked receive() returns Err(ReceiveError::Disconnected) and try_receive() returns Err(TryReceiveError::Disconnected). A disconnected channel stays disconnected: a sender is made only with the channel or by cloning a live one.

When the Receiver is dropped, send() returns Err(SendError) and try_send() Err(TrySendError::Disconnected), each handing the value back, rather than queueing into a channel nobody will drain.

Underneath, a heap inner holds a Mutex over the channel's state — a raw singly-linked node queue with its length, plus a live-sender count and a total-handle refcount — a ConditionVariable the receiver waits on, and one a sender waits on for room. The inner is reclaimed when the last handle of either kind drops. Values move out of dequeued nodes through raw pointers, so the move-checker sees each as a clean transfer — no aliasing, no double free.

Trait implementations

Sender

implement<T> trait Drop for struct Sender<T>

Receiver

implement<T> trait Drop for struct Receiver<T>
implement<T> trait Iterator<T> for struct Receiver<T>

SendError

implement<T> trait Display for struct SendError<T>
implement<T> trait Debug for struct SendError<T>
implement<T> trait Error for struct SendError<T>

TrySendError

implement<T> trait Display for enum TrySendError<T>
implement<T> trait Debug for enum TrySendError<T>
implement<T> trait Error for enum TrySendError<T>

ReceiveError

implement trait Display for enum ReceiveError
implement trait Error for enum ReceiveError

TryReceiveError

implement trait Display for enum TryReceiveError
implement trait Error for enum TryReceiveError

ReceiveTimeoutError

implement trait Display for enum ReceiveTimeoutError
implement trait Error for enum ReceiveTimeoutError

Receiver::drop drains and drops whatever is still queued.