gpt4 book ai didi

rust - 如何一次执行多个异步函数并得到结果?

转载 作者:行者123 更新时间:2023-12-03 11:27:35 24 4
gpt4 key购买 nike

我尝试过 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

最佳答案

对于两个 future ,就像你一样,使用 future::join

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

async fn speak() {
let (_s, _g) = future::join(say(), greet()).await;
}
有三、四和五输入 future 的变体: join3 , join4 , join5 .
还有 try_join (和 try_join3 try_join4 try_join5 )用于当您的 future 返回 Result 时.
join 是另一种处理静态数量的 future 加入的方法。
如果需要支持动态数量 future ,可以使用 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;
}
请注意,此代码可以同时运行 future ,但不会并行运行它们。对于并行执行,您需要引入某种任务。
也可以看看:
  • 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?
  • 关于rust - 如何一次执行多个异步函数并得到结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63463579/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com