观看 Rust 中的频道

问题描述 投票:0回答:1

我需要帮助来理解borrow()和borrow_and_update(),两者看起来都与我相似。

#[tokio::main]
async fn main() {
    use tokio::sync::watch;
    use tokio::time::{Duration, sleep};

    let (tx, mut rx) = watch::channel("hello");
    let mut rx2 = tx.subscribe();
    tokio::spawn(async move {
        loop {
            println!("{}! ", *rx2.borrow_and_update());
            if rx.changed().await.is_err() {
                break;
            }
        }
    });

    sleep(Duration::from_millis(1000)).await;
    tx.send("world").unwrap();
    sleep(Duration::from_millis(1000)).await;
}

这是我正在使用的示例,使用

borrow()
borrow_and_update()
时我看不出有任何区别。
我已阅读文档,其中说
borrow_and_seen()
将标记所见的值,而
borrow
则不会。
谁能举一个合适的例子来帮助我理解这两个。

asynchronous rust watch rust-tokio
1个回答
0
投票

文档中有一个 专门的部分介绍何时使用 which:

borrow_and_update
borrow

如果接收者打算循环等待来自

changed
的通知,
Receiver::borrow_and_update()
应该优先于
Receiver::borrow()
。这避免了新值出现的潜在竞争 在
changed
准备就绪和正在读取值之间发送。 (如果 使用
Receiver::borrow()
,循环可能会以相同的值运行两次。)

如果接收者只对当前值感兴趣,并不打算 等待更改,然后可以使用

Receiver::borrow()
。可能会更多 使用起来很方便
borrow
因为它是
&self
方法—
borrow_and_update
需要
&mut self

© www.soinside.com 2019 - 2024. All rights reserved.