Using the futures
crate.
I have a vec of futures which return a bool and I want to wait specifically for the future that returns true.
consider the following pool of futures.
async fn async_function(guess: u8) -> bool {
let random_wait = rand::thread_rng().gen_range(0..2);
std::thread::sleep(std::time::Duration::from_secs(random_wait));
println!("Running guess {guess}");
guess == 231
}
fn main() {
let mut pool: Vec<impl Future<Output = bool>> = vec![];
for guess in 0..=255 {
pool.push(async_function(guess));
}
}
- How do I wait for the futures in the vec?
- Is it possible to wait until only one future returns true?
- Can I identify the value of guess for the future that returns true?
I'm new to async rust, so I've been looking at the async-book.
From there, these are the options I've considered:
join!
waits until all threads are done, so that doesn't work for me since I want to drop the remaining futures.select!
doesn't seem to be an option, because I need to specify the specific future in the select block and I'm not about to make 255 line select.try_join!
is tempting me to break semantics and have my async_function returnErr(guess)
so that it causes the try_join to exit and return the value I want.I tried using
async_fn(guess).boxed.into_stream()
and then usingselect_all
fromfutures::stream
but it doesn't seem to run concurrently. I see my async functions running in order.