[][src]Function async_std::sync::channel

pub fn channel<T>(cap: usize) -> (Sender<T>, Receiver<T>)
This is supported on unstable only.

Creates a bounded multi-producer multi-consumer channel.

This channel has a buffer that can hold at most cap messages at a time.

Senders and receivers can be cloned. When all senders associated with a channel get dropped, it becomes closed. Receive operations on a closed and empty channel return RecvError instead of trying to await a message when using Receiver::recv or None when used as a Stream.

Panics

If cap is zero, this function will panic.

Examples

use std::time::Duration;

use async_std::sync::channel;
use async_std::task;

let (s, r) = channel(1);

// This call returns immediately because there is enough space in the channel.
s.send(1usize).await;

task::spawn(async move {
    // This call will have to wait because the channel is full.
    // It will be able to complete only after the first message is received.
    s.send(2).await;
});

task::sleep(Duration::from_secs(1)).await;
assert_eq!(r.recv().await?, 1);
assert_eq!(r.recv().await?, 2);