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;
async fn foo(i: u32) -> u32 {
10 + i
}
fn main() {
block_on(async {
let futures = vec![foo(1), foo(2), foo(3)];
assert_eq!(join_all(futures).await, [11, 12, 13]);
});
}