如何解决如何一次执行多个异步功能并获得结果?
我已经尝试了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::join
use futures::{executor,future}; // 0.3.5
async fn speak() {
let (_s,_g) = future::join(say(),greet()).await;
}
有三种,四种和五种输入期货的变体:join3
,join4
,join5
。
当您的未来返回Result
时,还有try_join
(和try_join3
,try_join4
,try_join5
)。
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;
}
请注意,此代码可以同时运行期货,但不能并行运行。对于并行执行,您需要引入一些任务。
另请参阅:
- 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?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。