use futures::future::join_all;
use std::time::Instant;
use tokio::task::JoinHandle;
fn sleep_ms(start: &Instant, id: u64, duration_ms: u64) {
std::thread::sleep(std::time::Duration::from_millis(duration_ms));
println!(
"future {id} slept for {duration_ms}ms, finished after {}ms",
start.elapsed().as_millis()
);
}
#[tokio::main(flavor = "current_thread")]
async fn main() {
let start = Instant::now();
let v: Vec<JoinHandle<()>> = (1..=10)
.map(|t| {
tokio::task::spawn_blocking(move || {
sleep_ms(&start, t, t * 10);
})
})
.collect();
for k in v {
if let Err(e) = k.await {
eprintln!("Error in spawned task: {:?}", e);
}
}
}
为什么 for k in sleep_futures.iter()不行,需要使用 for k in sleep_futures?