说明
在前一节,我们简单介绍了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"] }
网友评论