【tokio】broadcast

tokio::sync::broadcast

多生成者、多消费者的广播队列。每个发送的值都被所有消费者收到。

示例

use tokio::sync::broadcast;
use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() {
    let (tx, mut rx1) = broadcast::channel(16);
    let mut rx2 = tx.subscribe();
    let mut rx3 = tx.subscribe();
    let tx2 = tx.clone();
    
    tokio::spawn(async move {
        loop {
            println!("rx1: {}", rx1.recv().await.unwrap());
        }
    });

    tokio::spawn(async move {
        loop {
            println!("rx2: {}", rx2.recv().await.unwrap());
        }
    });

    tokio::spawn(async move {
        loop {
            println!("rx3: {}", rx3.recv().await.unwrap());
        }
    });
    
    tx.send(10).unwrap();
    tx2.send(20).unwrap();    
    sleep(Duration::from_millis(1)).await;
}

输出

rx1: 10
rx1: 20
rx2: 10
rx2: 20
rx3: 10
rx3: 20

你可能感兴趣的:(tokio,tokio)