美文网首页RUST编程
009 Rust 异步编程,select 宏中的使用 defau

009 Rust 异步编程,select 宏中的使用 defau

作者: 令狐壹冲 | 来源:发表于2020-07-17 21:18 被阅读0次

说明

在前一节,我们简单介绍了select宏。其实在select宏中,还可使用default和complete,前者表示没有分支完成,而后者则表示所有的分支都已经完成并且不会再取得进展的情况。

示例

  • 源代码
use futures::{future, select};
use tokio::runtime::Runtime;

async fn count() {
    let mut a_fut = future::ready(4);
    let mut b_fut = future::ready(6);
    let mut total = 0;

    loop {
        select! {
            a = a_fut => total += a,
            b = b_fut => total += b,
            complete => break,
            default => unreachable!(), // never runs (futures are ready, then complete)
        };
    }
    assert_eq!(total, 10);
}

fn main() {
    let mut runtime = Runtime::new().unwrap();
    runtime.block_on(count());  
}

  • 配置
[dependencies]
futures = "0.3.5"
tokio = { version = "0.2", features = ["full"] }

相关文章

网友评论

    本文标题:009 Rust 异步编程,select 宏中的使用 defau

    本文链接:https://www.haomeiwen.com/subject/uobnhktx.html