gpt4 book ai didi

rust - 如何等待第一个k future ?

转载 作者:行者123 更新时间:2023-12-04 11:47:04 25 4
gpt4 key购买 nike

假设我们有 n 个服务器,我们只需要 k < n 个响应。
我知道 futures::join_all 可用于等待所有 n 个 future ,但我希望我的程序在 k 个响应后完成等待。
是否有类似于 join_all 的东西可以用来等待前 k 个响应?

最佳答案

您可以使用 streams (异步迭代器)为此。您可以使用 FuturesUnordered 作为一个无序的 future 集合,它可以用作一个流,您可以在其中按照它们完成的顺序获得每个 future 的结果。然后你可以把它和 .take(n) 结合起来只取第一个 n流的项目,然后 .collect::<Vec<_>>() 等待流结束并在 Vec 中收集结果:

use futures::prelude::*;
use futures::stream::FuturesUnordered;

let futures = vec![
// assume `f(n, t)` = sleep for `t` millis, then return `n`
f(1, 1000),
f(2, 10),
f(3, 105),
f(4, 40),
f(5, 70),
f(6, 270),
];

// create unordered collection of futures
let futures = futures.into_iter().collect::<FuturesUnordered<_>>();

// use collection as a stream, await only first 4 futures to complete
let first_4 = futures.take(4).collect::<Vec<_>>().await;

// note: any remaining futures will be cancelled automatically when the
// stream is consumed

// check with expected result, based on the order of completion
assert_eq!(first_4, vec![2, 4, 5, 3]);
Playground example

编辑:如果你还想获得完成 future 的索引,你可以使用这个:
// create unordered collection of futures with indices
let futures = futures
.into_iter()
.enumerate()
.map(|(i, fut)| fut.map(move |res| (i, res)))
.collect::<FuturesUnordered<_>>()
Playground example

关于rust - 如何等待第一个k future ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68448854/

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