rust异步之asyncawaitfuture
Posted rayylee
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了rust异步之asyncawaitfuture相关的知识,希望对你有一定的参考价值。
1. 简单的异步 async
The most common way to run a Future is to .await it. When .await is called on a Future, it will attempt to run it to completion.
执行 Future的最简单方法就是调用 await
use futures::executor::block_on;
async fn say_hi()
println!("nice");
fn main()
let future = say_hi();
// block the current thread until provided future
block_on(future);
使用
async
来修饰一个方法, 表示此方法是一个异步任务, 然后在主线程里使用一个执行器宏block_on
来等待运行结果
2. 关键字 await
async fn lear_song()
println!("learn song");
async fn sing_song()
println!("sing song");
async fn dance()
println!("learn dance");
async fn learn_and_sing()
// study song, and wait
let song = lear_song().await;
// then sing song
sing_song().await;
async fn async_main()
let f1 = learn_and_sing();
let f2 = dance();
futures::join!(f1,f2);
fn main()
block_on(async_main());
println!("done");
- 在一个
async
方法中, 可以执行其他异步任务. 但如果需要顺序执行这些异步任务时, 就需要在上一个任务的后面,执行await
方法.- 如果想实现
barrier
类似的效果, 可以通过futures::join
方法来实现.
3. futures
使用futures实现并发
use futures::executor::block_on;
use futures::future::join_all, pending, select_all;
use futures::prelude::*;
async fn a(a: i32, b: i32) -> i32
a + b
async fn b(a: i32, b: i32) -> i32
a - b
async fn c(a: i32, b: i32) -> i32
pending().await
fn main()
let r = block_on(async
println!("", a(1, 2).await);
println!("", b(1, 2).await);
async fn foo(i: u32) -> u32
i * 10
let futures = vec![foo(1), foo(2), foo(3)];
let all_finished = join_all(futures).await;
println!(":?", all_finished);
// let first_finished = select_all(futures).await;
// println!(":?", first_finished);
"block_on result"
);
println!("", r)
以上是关于rust异步之asyncawaitfuture的主要内容,如果未能解决你的问题,请参考以下文章