한 번에 여러 비동기 함수를 실행하고 결과를 얻는 방법은 무엇입니까?

Aug 18 2020

Tokio 작업을 시도했지만 한 번에 여러 작업을 실행하는 작업 예제가 없습니다. 이 코드에 어떤 문제가 있습니까?

fn main() {
    block_on(speak());
}

async fn speak() {
    let hold = vec![say(), greet()];
    let results = join_all(hold).await;
}

async fn say() {
    println!("hello");
}

async fn greet() {
    println!("world");
}

다음은 컴파일러 출력입니다.

error[E0308]: mismatched types
  --> sync\src\main.rs:14:27
   |
14 |     let hold = vec![say(),greet()];
   |                           ^^^^^^^ expected opaque type, found a different opaque type
...
23 | async fn greet(){
   |                 - the `Output` of this `async fn`'s found opaque type
   |
   = note:     expected type `impl core::future::future::Future` (opaque type at <sync\src\main.rs:19:15>)
           found opaque type `impl core::future::future::Future` (opaque type at <sync\src\main.rs:23:17>)
   = note: distinct uses of `impl Trait` result in different opaque types

답변

6 Shepmaster Aug 18 2020 at 20:06

두 가지 미래에 대해 future::join

use futures::{executor, future}; // 0.3.5

async fn speak() {
    let (_s, _g) = future::join(say(), greet()).await;
}

변종 셋, 넷, 다섯 입력 선물에 대한이 있습니다 join3, join4, join5.

이 또한 try_join(와 try_join3, try_join4, try_join5당신의 미래가 반환 될 때를 위해) Result.

매크로 join는 결합 할 정적 인 수의 선물을 처리하는 또 다른 방법입니다.

동적 수의 퓨처를 지원해야하는 경우 future::join_all(또는 try_join_all)을 사용할 수 있지만 모두 한 종류의 벡터가 있어야합니다. FutureExt::boxed(또는 FutureExt::boxed_local)을 통해 가장 쉽습니다 .

use futures::{executor, future, FutureExt}; // 0.3.5

async fn speak() {
    let futures = vec![say().boxed(), greet().boxed()];
    let _results = future::join_all(futures).await;
}

Note that this code can run the futures concurrently but will not run them in parallel. For parallel execution, you need to introduce some kind of tasks.

See also:

  • How can I join all the futures in a vector without cancelling on failure like join_all does?
  • Join futures with limited concurrency
  • How can I perform parallel asynchronous HTTP GET requests with reqwest?
  • How do I create a heterogeneous collection of objects?
  • What is the purpose of async/await in Rust?
  • What is the difference between concurrency and parallelism?