天天看点

004 Rust 异步编程,async await 的详细用法

我们之前简单介绍了async/.await的用法,本节将更详细的介绍async/.await。

async的用法

async主要有两种用法:async函数和asyn代码块(老版本书中说的是三种主要的用法,多了一个async闭包)。这几种用法都会返回一个Future对象,如下:

async fn foo() -> u8 { 5 }

fn bar() -> impl Future<Output = u8> {
    // `Future<Output = u8>`.
    async {
        let x: u8 = foo().await;
        x + 5
    }
}

fn baz() -> impl Future<Output = u8> {
    // implements `Future<Output = u8>`
    let closure = async |x: u8| {
        let y: u8 = bar().await;
        y + x
    };
    closure(5)
}      

async转化的Future对象和其它Future一样是具有惰性的,即在运行之前什么也不做。运行Future最常见的方式是.await。

async的生命周期

考虑示例:

async fn foo(x: &u8) -> u8 { *x }      

根据我们前面的知识,那么该函数其实等价于如下:

fn foo<'a>(x: &'a u8) -> impl Future<Output = ()> + 'a {
    async { *x }
}      

这个异步函数返回一个Future对象。如果我们把这个Future对象在线程间进行传递,那么则存在生命周期的问题。如下:

//这种调用就会存在生命周期的问题
fn bad() -> impl Future<Output = ()> {
    let x = 5;
    foo(&x) // ERROR: `x` does not live long enough
}      

正确的调用方式如下:

fn good() -> impl Future<Output = ()> {
    async {
        let x = 5;
        foo(&x).await;
    }
}      

说明:通过将变量移动到async中,将延长x的生命周期和foo返回的Future生命周期一致。

async move

示例如下

  • 配置文件:
//Cargo.toml中添加
[dependencies]
futures = "0.3.4      
  • 源码:
//src/main.rs
use futures::executor;
async fn move_block() {
    let my_string = "foo".to_string();
    let f = async move {
        println!("{}", my_string);
    };
    // println!("{}", my_string); //此处不能再使用my_string
    f.await
}
fn main() {
    executor::block_on(move_block());
}      

多线程

继续阅读