Function crossbeam::channel::bounded

source ·
pub fn bounded<T>(cap: usize) -> (Sender<T>, Receiver<T>)
Expand description

Creates a channel of bounded capacity.

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

A special case is zero-capacity channel, which cannot hold any messages. Instead, send and receive operations must appear at the same time in order to pair up and pass the message over.

§Examples

A channel of capacity 1:

use std::thread;
use std::time::Duration;
use crossbeam_channel::bounded;

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

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

thread::spawn(move || {
    // This call blocks the current thread because the channel is full.
    // It will be able to complete only after the first message is received.
    s.send(2).unwrap();
});

thread::sleep(Duration::from_secs(1));
assert_eq!(r.recv(), Ok(1));
assert_eq!(r.recv(), Ok(2));

A zero-capacity channel:

use std::thread;
use std::time::Duration;
use crossbeam_channel::bounded;

let (s, r) = bounded(0);

thread::spawn(move || {
    // This call blocks the current thread until a receive operation appears
    // on the other side of the channel.
    s.send(1).unwrap();
});

thread::sleep(Duration::from_secs(1));
assert_eq!(r.recv(), Ok(1));