asynchronous - 如何在 Rust 中竞赛 future 集合?

标签 asynchronous concurrency rust future

给定一个集合 Future s,说一个 Vec<impl Future<..>> ,我怎样才能阻止和运行所有 Future s 同时直到第一个 Future准备好了?
我能找到的最接近的特征是 select macro (这也是 available in Tokio )。不幸的是,它只适用于明确的数字 Future s,而不是处理它们的集合。
Javascript 中有一个与此功能等效的功能,称为 Promise.race .有没有办法在 Rust 中做到这一点?
或者也许有一种方法可以使用另一种模式(也许是 channel )来实现此用例?

最佳答案

我想出了一个使用 select_all function from the futures 的解决方案图书馆。
下面是一个简单的例子来演示如何使用它来竞争 future 集合:

use futures::future::select_all;
use futures::FutureExt;
use tokio::time::{delay_for, Duration};

async fn get_async_task(task_id: &str, seconds: u64) -> &'_ str {
    println!("starting {}", task_id);
    let duration = Duration::new(seconds, 0);

    delay_for(duration).await;

    println!("{} complete!", task_id);
    task_id
}

#[tokio::main]
async fn main() {
    let futures = vec![

        // `select_all` expects the Futures iterable to implement UnPin, so we use `boxed` here to
        // allocate on the heap:
        // https://users.rust-lang.org/t/the-trait-unpin-is-not-implemented-for-genfuture-error-when-using-join-all/23612/3
        // https://docs.rs/futures/0.3.5/futures/future/trait.FutureExt.html#method.boxed

        get_async_task("task 1", 5).boxed(),
        get_async_task("task 2", 4).boxed(),
        get_async_task("task 3", 1).boxed(),
        get_async_task("task 4", 2).boxed(),
        get_async_task("task 5", 3).boxed(),
    ];

    let (item_resolved, ready_future_index, _remaining_futures) =
        select_all(futures).await;

    assert_eq!("task 3", item_resolved);
    assert_eq!(2, ready_future_index);
}
这是上面代码的链接:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f32b2ed404624c1b0abe284914f8658d
感谢@Herohtar 的建议 select_all在上面的评论中!

关于asynchronous - 如何在 Rust 中竞赛 future 集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63715918/

相关文章:

c# - 秒表计时异步/等待方法不准确

node.js - 调用在 Controller 中同步工作的函数 - Node

python - Celery 任务子进程填满并发槽?

Java:SingleThreadScheduledExecutor & java.util.concurrent.RejectedExecutionException

concurrency - 并发算法思考并在 Go 中学习

macros - 如何将文件的内容作为参数包含在宏中?

asynchronous - 如何从带有回调的 C# 方法创建 F# 异步?

php - Rack 的轻量级流式 HTTP 代理(Ruby CPU 轻型 HTTP 客户端库)

rust - 闭包: expected a closure that implements the `Fn` trait,内部的Arc <Mutex <T >>,但此闭包仅实现 `FnOnce`

rust - 使用不同的实现返回 Trait 实现