[Rust-async-book]--3--async/.await[翻译]

In the first chapter, we took a brief look at async/.await and used it to build a simple server. This chapter will discuss async/.await in greater detail, explaining how it works and how async code differs from traditional Rust programs.
在第一章中,我们简要介绍了async/.await,并使用它构建了一个简单的服务器。本章将更详细地讨论async/.await,解释它的工作原理以及异步代码与传统Rust程序的区别。

async/.await are special pieces of Rust syntax that make it possible to yield control of the current thread rather than blocking, allowing other code to make progress while waiting on an operation to complete.
async/.await是一种特殊的Rust语法,它使您能够产生对当前线程的控制,而不是阻塞,从而允许其他代码在等待操作完成时取得进展。

There are two main ways to use async: async fn and async blocks. Each returns a value that implements the Future trait:
使用async有两种主要方法:async fn和async块。每个函数都返回一个实现 Future trait 的值:

// `foo()` returns a type that implements `Future`.
// 'foo()`返回实现'Future'的类型。

// `foo().await` will result in a value of type `u8`.
// 'foo().await' 将产生'u8'类型的值。
async fn foo() -> u8 { 5 }

fn bar() -> impl Future {
    // This `async` block results in a type that implements
    // `Future`.
    async {
        let x: u8 = foo().await;
        x + 5
    }
}

As we saw in the first chapter, async bodies and other futures are lazy: they do nothing until they are run. 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. If the Future is blocked, it will yield control of the current thread. When more progress can be made, the Future will be picked up by the executor and will resume running, allowing the .await to resolve.
正如我们在第一章中看到的,异步体和其他futures 是 lazy :它们在运行之前什么也不做。管理 futures 最常见的方法是。.await它。当.await在 Future 调用时,它将尝试运行它直到完成。如果 Future 受阻,它将产生对当前线程的控制。当可以取得更多的进展时,Future 将由executor 拾取,并将继续运行,允许.await解决。

async Lifetimes

Unlike traditional functions, async fns which take references or other non-'static arguments return a Future which is bounded by the lifetime of the arguments:
与传统函数不同,采用引用或其他非“静态参数”的异步fn返回的 Future 受参数生存期的限制:

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

// Is equivalent to this function:
fn foo_expanded<'a>(x: &'a u8) -> impl Future + 'a {
    async move { *x }
}

This means that the future returned from an async fn must be .awaited while its non-'static arguments are still valid. In the common case of .awaiting the future immediately after calling the function (as in foo(&x).await) this is not an issue. However, if storing the future or sending it over to another task or thread, this may be an issue.
这意味着当异步fn的非静态参数仍然有效时,它返回的future必须是.awaited。在通常的情况下,在调用函数后立即等待future(如foo(&x).await)这不是问题。但是,如果存储future 或将其发送到其他任务或线程,这可能是一个问题。

One common workaround for turning an async fn with references-as-arguments into a 'static future is to bundle the arguments with the call to the async fn inside an async block:
将引用为参数的异步fn转换为“静态未来”的一个常见解决方法是将参数与异步块内对异步fn的调用绑定:

fn bad() -> impl Future {
    let x = 5;
    borrow_x(&x) // ERROR: `x` does not live long enough
}

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

By moving the argument into the async block, we extend its lifetime to match that of the Future returned from the call to good.
通过将参数移到异步块中,我们将其生存期延长,以匹配从调用返回到good的将来的生存期。

async move

async blocks and closures allow the move keyword, much like normal closures. An async move block will take ownership of the variables it references, allowing it to outlive the current scope, but giving up the ability to share those variables with other code:
异步块和闭包允许使用move关键字,这与普通闭包很相似。异步移动块将拥有它引用的变量的所有权,允许它在当前作用域中存在,但放弃了与其他代码共享这些变量的能力:

/// `async` block:
///
/// Multiple different `async` blocks can access the same local variable
/// so long as they're executed within the variable's scope
///多个不同的“async”块可以访问同一个局部变量
///只要它们在变量的作用域内执行
async fn blocks() {
    let my_string = "foo".to_string();

    let future_one = async {
        // ...
        println!("{}", my_string);
    };

    let future_two = async {
        // ...
        println!("{}", my_string);
    };

    // Run both futures to completion, printing "foo" twice:
   //运行两个futures以完成,打印“foo”两次:
    let ((), ()) = futures::join!(future_one, future_two);
}

/// `async move` block:
///
/// Only one `async move` block can access the same captured variable, since
/// captures are moved into the `Future` generated by the `async move` block.
/// However, this allows the `Future` to outlive the original scope of the
/// variable:
//////只有一个“async move”块可以访问同一个捕获的变量,因为捕获被移动到“async move”块生成
//////的“Future”中。但是,这允许“Future”比变量的原始范围长:

fn move_block() -> impl Future {
    let my_string = "foo".to_string();
    async move {
        println!("{}", my_string);
    }
}

'.await'ing on a Multithreaded Executor

Note that, when using a multithreaded Future executor, a Future may move between threads, so any variables used in async bodies must be able to travel between threads, as any .await can potentially result in a switch to a new thread.
注意,当使用多线程 Future executor时,Future 可能在线程之间移动,因此异步主体中使用的任何变量都必须能够在线程之间移动,就像任何一样。等待可能导致切换到新线程。

This means that it is not safe to use Rc, &RefCell or any other types that don't implement the Send trait, including references to types that don't implement the Sync trait.
这意味着使用Rc,&RefCell或任何其他不实现发送特征的类型(包括对不实现同步特征的类型的引用)是不安全的。

(Caveat: it is possible to use these types so long as they aren't in scope during a call to .await.)
(注意:只要这些类型在调用.await期间不在作用域内,就可以使用它们。)

Similarly, it isn't a good idea to hold a traditional non-futures-aware lock across an .await, as it can cause the threadpool to lock up: one task could take out a lock, .await and yield to the executor, allowing another task to attempt to take the lock and cause a deadlock. To avoid this, use the Mutex in futures::lock rather than the one from std::sync.

类似地,在.await中持有traditional non-futures-aware lock 也不是一个好主意,因为它可能导致线程池锁定:一个任务可以取出一个锁,.await并让步于executor,从而允许另一个任务尝试获取锁并导致死锁。要避免这种情况,请使用futures::lock中的互斥锁,而不是std::sync中的互斥锁。

你可能感兴趣的:([Rust-async-book]--3--async/.await[翻译])