I have the following async function (implementation is not important) :
async fn long_task(task_number: i32) {
// do some long work
println!("Task {} executed", task_number);
}
I want to run n times this function concurrently, so I defined this function :
async fn execute_long_tasks_async(n: i32) {
let mut futures = Vec::new();
for i in 1..=n {
futures.push(long_task(i));
}
futures::future::join_all(futures).await;
}
I'm using the join_all function to wait until all tasks are executed. Then I call this function in my main :
fn main() {
futures::executor::block_on(execute_long_tasks_async(3));
}
My issue is that the tasks are run sequentially :
Executing task 1
Task 1 executed
Executing task 2
Task 2 executed
Executing task 3
Task 3 executed
But I would have expect it runs concurrently, and I would get something like :
Executing task 1
Executing task 3
Executing task 2
Task 1 executed
Task 3 executed
Task 2 executed
Is there an alternative to futures::future::join_all to run all tasks in parallel ?
I'd like to use await to create a simple example demonstrating async and await.