gpt4 book ai didi

rust - 如何在循环中生成异步方法?

转载 作者:行者123 更新时间:2023-12-03 11:41:42 28 4
gpt4 key购买 nike

我有一个具有 resolve() 的对象向量使用 reqwest 的方法查询外部 Web API。我打电话后resolve()每个对象上的方法,我想打印每个请求的结果。
这是我编译和工作的半异步代码(但不是真正异步的):

for mut item in items {
item.resolve().await;

item.print_result();
}
我试过使用 tokio::join!产生所有异步调用并等待它们完成,但我可能做错了什么:
tokio::join!(items.iter_mut().for_each(|item| item.resolve()));
这是我得到的错误:
error[E0308]: mismatched types
--> src\main.rs:25:51
|
25 | tokio::join!(items.iter_mut().for_each(|item| item.resolve()));
| ^^^^^^^^^^^^^^ expected `()`, found opaque type
|
::: src\redirect_definition.rs:32:37
|
32 | pub async fn resolve(&mut self) {
| - the `Output` of this `async fn`'s found opaque type
|
= note: expected unit type `()`
found opaque type `impl std::future::Future`
我如何调用 resolve()一次用于所有实例的方法?

这段代码反射(reflect)了答案——现在我正在处理我不太理解的借用检查器错误——我应该用 'static 注释我的一些变量吗? ?
let mut items = get_from_csv(path);

let tasks: Vec<_> = items
.iter_mut()
.map(|item| tokio::spawn(item.resolve()))
.collect();

for task in tasks {
task.await;
}

for item in items {
item.print_result();
}
error[E0597]: `items` does not live long enough
--> src\main.rs:18:25
|
18 | let tasks: Vec<_> = items
| -^^^^
| |
| _________________________borrowed value does not live long enough
| |
19 | | .iter_mut()
| |___________________- argument requires that `items` is borrowed for `'static`
...
31 | }
| - `items` dropped here while still borrowed

error[E0505]: cannot move out of `items` because it is borrowed
--> src\main.rs:27:17
|
18 | let tasks: Vec<_> = items
| -----
| |
| _________________________borrow of `items` occurs here
| |
19 | | .iter_mut()
| |___________________- argument requires that `items` is borrowed for `'static`
...
27 | for item in items {
| ^^^^^ move out of `items` occurs here

最佳答案

由于您想并行等待 future ,您可以spawn它们变成并行运行的单个任务。由于它们彼此独立运行,并且与产生它们的线程无关,因此您可以按任何顺序等待它们的句柄。
理想情况下,你会写这样的东西:

// spawn tasks that run in parallel
let tasks: Vec<_> = items
.iter_mut()
.map(|item| tokio::spawn(item.resolve()))
.collect();
// now await them to get the resolve's to complete
for task in tasks {
task.await.unwrap();
}
// and we're done
for item in &items {
item.print_result();
}
但这将被借用检查器拒绝,因为 item.resolve() 返回的 future 持有对 item 的借用引用.引用传递给 tokio::spawn()将它交给另一个线程,编译器无法证明 item将比那个线程长。 (当你想 send reference to local data to a thread 时遇到了同样的问题。)
对此有几种可能的解决方案;我觉得最优雅的方法是将项目移动到传递给 tokio::spawn() 的异步闭包中,并在任务完成后将它们交还给您。基本上你消耗了 items vector 来创建任务并立即从等待的结果中重新构建它:
// note the use of `into_iter()` to consume `items`
let tasks: Vec<_> = items
.into_iter()
.map(|mut item| {
tokio::spawn(async {
item.resolve().await;
item
})
})
.collect();
// await the tasks for resolve's to complete and give back our items
let mut items = vec![];
for task in tasks {
items.push(task.await.unwrap());
}
// verify that we've got the results
for item in &items {
item.print_result();
}
playground 中的可运行代码.
请注意 futures crate 包含一个 join_all 功能类似于您需要的功能,除了它轮询单个 future 而不确保它们并行运行。我们可以写一个泛型 join_parallel使用 join_all ,但也使用 tokio::spawn获得并行执行:
async fn join_parallel<T: Send + 'static>(
futs: impl IntoIterator<Item = impl Future<Output = T> + Send + 'static>,
) -> Vec<T> {
let tasks: Vec<_> = futs.into_iter().map(tokio::spawn).collect();
// unwrap the Result because it is introduced by tokio::spawn()
// and isn't something our caller can handle
futures::future::join_all(tasks)
.await
.into_iter()
.map(Result::unwrap)
.collect()
}
使用此函数,回答问题所需的代码可归结为:
let items = join_parallel(items.into_iter().map(|mut item| async {
item.resolve().await;
item
})).await;
for item in &items {
item.print_result();
}
同样, playground 中的可运行代码.

关于rust - 如何在循环中生成异步方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63434977/

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