rust异步之async、await、future

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");
}
  1. 在一个async方法中, 可以执行其他异步任务. 但如果需要顺序执行这些异步任务时, 就需要在上一个任务的后面,执行await方法.
  2. 如果想实现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]);    
    });
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值