Function crossbeam_channel::bounded [] [src]

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

Creates a new channel of bounded capacity, returning the sender/receiver halves.

This type of channel has an internal buffer of length cap in messages get queued.

An interesting case is zero-capacity channel, also known as rendezvous channel. Such channel cannot hold any messages, since its buffer is of length zero. Instead, send and receive operations must execute at the same time in order to pair up and pass the message.

Examples

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

let (tx, rx) = bounded(1);

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

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

thread::sleep(Duration::from_secs(1));
assert_eq!(rx.recv(), Ok(1));
assert_eq!(rx.recv(), Ok(2));
use std::thread;
use std::time::Duration;
use crossbeam_channel::bounded;

let (tx, rx) = bounded(0);

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

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