advancedAsync
Async Spawn Tasks
Spawn concurrent tasks with tokio::spawn.
Async Spawn Tasks
Spawn concurrent tasks with tokio::spawn.
Difficulty
Advanced
Code
rust
use tokio;
async fn process(id: u32) -> u32 {
// simulate work
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
id * 2
}
#[tokio::main]
async fn main() {
let mut handles = vec![];
for i in 0..5 {
handles.push(tokio::spawn(process(i)));
}
let mut results = vec![];
for handle in handles {
results.push(handle.await.unwrap());
}
println!("results: {:?}", results);
}Explanation
tokio::spawn creates lightweight async tasks.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the async category to build a complete understanding of this topic.