I'm re-asking a question I asked here (Processing thread results in order they complete) because I'm still holding out hope that there is a Tokio-specific answer that is better than using channels, but perhaps channels is the best solution.
The following simple code spawns 10 tasks that each sleep for a random amount of time and then return some data. I would like the main thread to print the data from each task in the order that the tasks complete. But as written it prints in the order the tasks were created. I understand why it does this, but is there a better way than using channels to get the result I want? Is this something I should consider? futures::stream::futures_unordered::FuturesUnordered - Rust
use rand::Rng; // trait that must be in scope
use tokio::{
task,
time::{sleep, Duration},
};
#[tokio::main(worker_threads = 4)]
async fn main() {
let mut tasks = Vec::new();
for i in 0..10 {
// task::spawn requires a Future and using an async block provides this.
tasks.push(task::spawn(async move {
let ms = rand::thread_rng().gen_range(1000..3000);
sleep(Duration::from_millis(ms)).await;
(i, ms)
}));
}
for task in tasks {
let (task_number, sleep_ms) = task.await.unwrap();
println!("task {} slept for {}ms", task_number, sleep_ms);
}
println!("done");
}