Sub topic 6
Spawning concurrent tasks
This chapter covers tokio::spawn: what a task is, when it starts running, how it differs from a plain future, and what happens when you drop its handle. It assumes you know ownership and closures, you can add a crate with Cargo, and you have a runtime started with #[tokio::main]. The Send and 'static rules and panic handling get their own chapters, so they appear here only where you need them.
What a task is
A future does nothing until something polls it. If you call an async fn and .await it, the work runs inside the caller's task, one step after another. Nothing overlaps.
A task is a future that has been handed to the runtime to drive on its own. tokio::spawn takes a future, wraps it in a task, puts it in the scheduler, and returns a JoinHandle<T>. The runtime polls the task whenever it can make progress, independently of the code that spawned it.
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 async { ... } block is a future. spawn turns it into a task, and handle.await waits for the task's output. The unwrap is there because the handle resolves to a Result. The error case, a panicked or cancelled task, is covered in a later chapter.
When a spawned task starts
A spawned task is scheduled immediately. You do not need to .await the handle for the task to run. On the multi-thread runtime, an idle worker thread may pick it up before spawn even returns.
This differs from a bare future, which is lazy:
| Construct | Starts running | Runs on | Result |
|---|---|---|---|
| `let f = work();` | Only when polled by `.await` or a combinator | The current task | `f.await` |
| `tokio::join!(a, b)` | When the `join!` is awaited | The current task, interleaved | A tuple of outputs |
| `tokio::spawn(work())` | As soon as the scheduler can poll it | Any worker thread | `handle.await` returns a `Result` |
The practical consequence is that join! gives concurrency inside one task. spawn gives concurrency between tasks, and on a multi-thread runtime those tasks can also run in parallel on different threads.
A lifecycle diagram
A task can be polled many times, and possibly on different threads. Each time it returns Pending, the worker moves on to other tasks, which is why thousands of tasks can share a few threads.
Running many tasks at once
The common pattern is to spawn in a loop, keep the handles, and await them afterwards. Spawn all tasks first. If you await each handle inside the spawning loop, you serialize the work again.
use std::time::{Duration, Instant};
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let start = Instant::now();
let mut handles = Vec::new();
for i in 0..5u32 {
handles.push(tokio::spawn(async move {
sleep(Duration::from_millis(100)).await;
i * i
}));
}
let mut results = Vec::new();
for handle in handles {
results.push(handle.await.unwrap());
}
println!("{results:?} in {:?}", start.elapsed());
}All five sleeps overlap, so the total is a little over 100 ms rather than 500 ms. Results come back in spawn order because you await the handles in that order. The tasks themselves may finish in any order.
Using JoinSet
When you do not want to manage a Vec of handles, or you want results as each task finishes, use tokio::task::JoinSet. Dropping a JoinSet also aborts the tasks still in it, which makes cleanup simpler.
use tokio::task::JoinSet;
#[tokio::main]
async fn main() {
let mut set = JoinSet::new();
for i in 0..3u32 {
set.spawn(async move { i + 10 });
}
while let Some(result) = set.join_next().await {
println!("{}", result.unwrap());
}
}join_next returns tasks in completion order, not spawn order. It returns None once the set is empty.
Giving a task its data
A spawned future must own what it uses, because the task may outlive the function that created it. Use async move to move values in. For data you also need afterwards, clone it first.
#[tokio::main]
async fn main() {
let name = String::from("worker");
let for_task = name.clone();
let handle = tokio::spawn(async move {
format!("hello from {for_task}")
});
println!("{}", handle.await.unwrap());
println!("still have {name}");
}Without move, the block would borrow name, and the compiler would reject it with an error saying the borrowed value does not live long enough. This is the 'static requirement showing up. For larger shared values, clone an Arc instead of the data itself.
Dropping a handle does not cancel the task
Dropping a JoinHandle detaches the task. It keeps running, and you lose only the ability to read its result. This surprises people who expect Rust's usual "drop means cleanup" behavior.
A second trap is the end of main. When main returns, the runtime shuts down and any tasks still running are dropped. A task you spawned and never awaited may be cut off partway, or may never have been polled at all.
Choosing between spawn and join!
Use tokio::spawn when:
- The work should proceed independently of the code that started it, such as one task per accepted connection.
- You want parallelism across threads on the multi-thread runtime.
- The work must survive the caller being dropped or cancelled.
Use join! when:
- You need all results together before continuing.
- The futures can borrow local data, because nothing requires
'static. - You want to avoid the allocation and scheduling overhead of a task.
Spawning is cheap, since a task is a small heap allocation, but it is not free. Spawning a task for a trivial computation costs more than running it inline.
Common mistakes
- Awaiting each handle right after spawning it, which makes the work sequential.
- Forgetting
moveand hitting a borrow error about'static. - Assuming dropped handles cancel the task.
- Letting
mainreturn before background tasks finish. - Putting long CPU loops with no
.awaitinside a task. Such a task holds its worker thread and starves the others. Blocking work has its own chapter.
Exercise
The loop below is meant to run three 200 ms sleeps concurrently, but it takes about 600 ms. Why, and how do you fix it? Code: for i in 0..3 { tokio::spawn(async move { sleep(Duration::from_millis(200)).await; i }).await.unwrap(); }
Show answer
Each .await on the JoinHandle happens before the next iteration spawns its task, so only one task exists at a time and the sleeps run back to back. Fix it by spawning all tasks first and collecting the handles in a Vec, then awaiting them in a second loop. You can also use a JoinSet and call join_next in a loop after all spawns. The total then drops to about 200 ms.
Exercise
A program spawns a task that writes a log line after a 50 ms sleep, drops the returned JoinHandle, and then main returns immediately. Will the log line reliably appear? What should you change?
Show answer
No. Dropping the handle detaches the task but does not wait for it, and when main returns the runtime shuts down and drops unfinished tasks, so the sleep never completes. Keep the handle and .await it before main ends, or put the task in a JoinSet and drain it with join_next.