我有一个包含多个future的
另一个要求是,一旦一个future完成,我可能想要将一个新的future添加到
使用这样的函数,我的代码大致如下:
Vec
,我想并发地执行它们(但不一定是同时)。基本上,我正在寻找一种类似于tokio::select!
的select
函数,但接受一个future集合;或者,一种类似于futures::join_all
的函数,但在第一个future完成后返回。另一个要求是,一旦一个future完成,我可能想要将一个新的future添加到
Vec
中。使用这样的函数,我的代码大致如下:
use std::future::Future;
use std::time::Duration;
use tokio::time::sleep;
async fn wait(millis: u64) -> u64 {
sleep(Duration::from_millis(millis)).await;
millis
}
// This pseudo-implementation simply removes the last
// future and awaits it. I'm looking for something that
// instead polls all futures until one is finished, then
// removes that future from the Vec and returns it.
async fn select<F, O>(futures: &mut Vec<F>) -> O
where
F: Future<Output=O>
{
let future = futures.pop().unwrap();
future.await
}
#[tokio::main]
async fn main() {
let mut futures = vec![
wait(500),
wait(300),
wait(100),
wait(200),
];
while !futures.is_empty() {
let finished = select(&mut futures).await;
println!("Waited {}ms", finished);
if some_condition() {
futures.push(wait(200));
}
}
}
stream::iter(futures).try_for_each_concurrent
或future::try_join_all
。 - Martin Gallagher