Spawning tasks in Rust
tokio::spawn hands a future to the runtime and returns a JoinHandle.
use tokio::time::{sleep, Duration};
async fn work(id: u32) -> u32 {
sleep(Duration::from_millis(10 * id as u64)).await;
id * id
}
#[tokio::main]
async fn main() {
let mut handles = Vec::new();
for id in 1..=4 {
handles.push(tokio::spawn(work(id)));
}
for handle in handles {
println!("{}", handle.await.unwrap());
}
}
How it works
- Tasks are cheap: thousands per thread is normal.
- The handle resolves to the task's output.
- A spawned future must be
'static, so move what it needs.
Keywords and builtins used here
Vecasasyncawaitfnforinletmainmutu32u64usework
The run, in numbers
- Lines
- 18
- Characters to type
- 320
- Tokens
- 107
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 58 seconds.
Step 2 of 6 in Async with tokio, step 10 of 15 in Concurrency & async.