Function loole::bounded

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

Create a bounded channel with a limited maximum capacity.

Returns a tuple of a Sender and a Receiver, which can be used to send and receive messages, respectively. The channel has a limited capacity, which means that it can only hold a certain number of messages at a time. If the channel is full, calls to Sender::send will block until there is space available.

Bounded channels are useful for controlling the flow of data between threads. For example, you can use a bounded channel to prevent a producer thread from overwhelming a consumer thread.

Unlike an unbounded channel, if there is no space left for new messages, calls to Sender::send will block (unblocking once a receiver has made space). If blocking behaviour is not desired, Sender::try_send may be used.

Also ‘rendezvous’ channels are supported by loole. A bounded queue with a limited maximum capacity of zero will block senders until a receiver is available to take the value.

Producers can send and consumers can receive messages asynchronously or synchronously.

Examples

let (tx, rx) = loole::bounded(3);

tx.send(1).unwrap();
tx.send(2).unwrap();
tx.send(3).unwrap();

assert!(tx.try_send(4).is_err());

let mut sum = 0;
sum += rx.recv().unwrap();
sum += rx.recv().unwrap();
sum += rx.recv().unwrap();

assert!(rx.try_recv().is_err());

assert_eq!(sum, 1 + 2 + 3);