Tâches : tokio::spawn
Avancé// spawn lance une tâche concurrente ; JoinHandle permet d'attendre son résultat
let handle = tokio::spawn(async {
tokio::time::sleep(Duration::from_secs(1)).await;
"terminé"
});
let valeur = handle.await.unwrap(); // Result : erreur si la tâche a paniqué
// Plusieurs tâches
let mut handles = Vec::new();
for i in 0..5 {
handles.push(tokio::spawn(async move { i * 2 }));
}
for h in handles {
println!("{}", h.await.unwrap());
}
Les tâches lancées avec
spawndoivent être'static: utilisezasync movepour leur transférer la propriété des données (ou desArc).