I would like to run an arbitrary number of futures concurrently in Rust. For this, I created a simple program that simulates real work by calling thread::sleep
.
The calc()
function below pretends to do work by sleeping for 2 seconds, then the batch()
function calls it 3 times, I'm assuming, asynchronously via join_all
.
The problem is that this program executes for 6 seconds, not for 2 as I would expect.
What is the trick to make the futures in the vec!
run asynchronously?
use futures::future::join_all;
use futures::executor::block_on;
use std::thread;
use std::time::{Duration, SystemTime};
async fn calc(i: u32) -> u32 {
let seconds = Duration::from_secs(2);
thread::sleep(seconds);
i
}
async fn batch() -> Vec<u32> {
let futures = vec![calc(1), calc(2), calc(3)];
join_all(futures).await
}
fn main() {
let now = SystemTime::now();
let result = block_on(batch());
println!("Result: {:?} took {:?} seconds", result, now.elapsed().unwrap());
}