Sub topic 6
Spawning concurrent tasks
This chapter assumes you know Rust ownership and closures, and that you have a Tokio project running with #[tokio::main]. You should also know that an async fn returns a future that does nothing until it is polled.
What a task is
A task is a future that the runtime owns and schedules on its own. You create one with tokio::spawn. The call hands the future to the runtime and returns right away. The future then runs in the background, possibly on another worker thread, while your current code keeps going.
Spawning differs from .await. Awaiting a future runs it inside the current task and pauses the current task until it finishes. Spawning starts a separate task that makes progress independently.
A first spawned task
tokio::spawn returns a JoinHandle. Awaiting the handle gives you the task's result.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
sleep(Duration::from_millis(100)).await;
42
});
let value = handle.await.unwrap();
println!("task returned {value}");
}The handle's output is a Result. It is Err if the task panicked or was cancelled, which is why unwrap appears. A later chapter covers handling that error properly.
The task starts running as soon as you call spawn. You do not have to await the handle for the work to happen. If you drop the handle, the task keeps running and you lose the ability to get its result. This is called detaching.
Spawning many tasks
The usual pattern is to spawn in a loop and keep the handles in a Vec. Then you await each handle.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let mut handles = Vec::new();
for id in 0..5u32 {
handles.push(tokio::spawn(async move {
sleep(Duration::from_millis(100)).await;
id * 2
}));
}
for handle in handles {
let result = handle.await.unwrap();
println!("result {result}");
}
}All five tasks sleep at the same time, so the program takes about 100 ms, not 500 ms. The async move block takes ownership of id. Without move, the block would borrow id, and a spawned task cannot borrow from the function that created it.
The diagram shows the flow.
Common errors
- Forgetting
move. The compiler reports that the closure or block may outlive the borrowed value. Addmove, or clone the data first. - Expecting order. Tasks run in an order the runtime picks. Results come back in the order you await the handles, not the order tasks finish.
- Dropping the runtime early. When
mainreturns, the runtime shuts down and unfinished tasks are cancelled. Await your handles if the work must complete. - Spawning outside a runtime. Calling
tokio::spawnfrom plain synchronous code panics because no runtime is active.
Exercise
A program spawns three tasks that each sleep for 200 ms, then awaits all three handles in a loop. Roughly how long does it take, and why?
Show answer
About 200 ms. Each task starts running at the moment of tokio::spawn, so the three sleeps overlap. Awaiting the handles one after another only collects results. It does not delay the tasks.