Skip to main content

channel

Function channel 

Source
pub fn channel<T: Clone>(capacity: usize) -> (Sender<T>, Receiver<T>)
Expand description

Create a bounded, multi-producer, multi-consumer channel where each sent value is broadcasted to all active receivers.

Note: The provided capacity is rounded up to the next power of two. That rounded size is the number of messages the internal ring buffer can retain, and is what lag detection uses. For example, channel(3) behaves as if the capacity were 4.

All data sent on Sender will become available on every active Receiver in the same order as it was sent.

The Sender can be cloned to send to the same channel from multiple points in the process or it can be used concurrently from an Arc. New Receiver handles are created by calling Sender::subscribe.

If all Receiver handles are dropped, the send method will return a SendError. Similarly, if all Sender handles are dropped, the recv method will return a RecvError.

§Examples

use tokio::sync::broadcast;

let (tx, mut rx1) = broadcast::channel(16);
let mut rx2 = tx.subscribe();

tokio::spawn(async move {
    assert_eq!(rx1.recv().await.unwrap(), 10);
    assert_eq!(rx1.recv().await.unwrap(), 20);
});

tokio::spawn(async move {
    assert_eq!(rx2.recv().await.unwrap(), 10);
    assert_eq!(rx2.recv().await.unwrap(), 20);
});

tx.send(10).unwrap();
tx.send(20).unwrap();

§Panics

This will panic if capacity is equal to 0.

This pre-allocates space for capacity messages. Allocation failure may result in a panic or an allocation error.