跳到主要内容

channel

搜索

函数 channel 

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

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

Sender 发送的所有值 将对 Receiver 句柄可见。 仅最近发送的值对 Receiver 半可用。 所有中间值都将被丢弃。

§示例

以下示例打印 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")?;