[][src]Function piper::chan

pub fn chan<T>(cap: usize) -> (Sender<T>, Receiver<T>)

Creates a bounded multi-producer multi-consumer channel.

This channel has a buffer that holds at most cap messages at a time. If cap is zero, no messages can be stored in the channel, which means send operations must pair with receive operations in order to pass messages over.

Senders and receivers can be cloned. When all senders associated with a channel are dropped, remaining messages can still be received, but after that receive operations will return None. On the other hand, when all receivers are dropped, further send operation block forever.

Examples

use smol::{Task, Timer};
use std::time::Duration;

// Create a channel that can hold 1 message at a time.
let (s, r) = piper::chan(1);

// Sending completes immediately because there is enough space in the channel.
s.send(1).await;

let t = Task::spawn(async move {
    // This send operation is blocked because the channel is full.
    // It will be able to complete only after the first message is received.
    s.send(2).await;
});

// Sleep for a second and then receive both messages.
Timer::after(Duration::from_secs(1)).await;
assert_eq!(r.recv().await, Some(1));
assert_eq!(r.recv().await, Some(2));