跳到主要内容

channel

搜索

函数 channel 

源代码
pub fn channel<T>(init: T) -> (Sender<T>, Receiver<T>)
展开描述

创建一个新的 watch channel,返回“发送”和“接收”句柄。

Sender 发送的所有值将对 Receiver 句柄可见。只有最后发送的值可供 Receiver 端使用。所有中间值都会被 drop。

§示例

以下示例会打印 hello! world!

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

let (tx, mut rx) = watch::channel("hello");

tokio::spawn(async move {
    // Use the equivalent of a "do-while" loop so the initial value is
    // processed before awaiting the `changed()` future.
    loop {
        println!("{}! ", *rx.borrow_and_update());
        if rx.changed().await.is_err() {
            break;
        }
    }
});

sleep(Duration::from_millis(100)).await;
tx.send("world")?;