[][src]Function tokio::sync::broadcast::channel

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

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

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;

#[tokio::main]
async fn main() {
    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();
}