Sub topic 15
Shutting down cleanly
This chapter assumes you can spawn tasks, use mpsc channels, and know that select! drops the futures that lose. A clean shutdown means every task gets a chance to finish its current work and release resources before the process exits. Without one, main returning kills all spawned tasks mid-operation.
Why tasks need to be told to stop
When main returns, the runtime drops and any task still running is cancelled at its next .await. Dropping a JoinHandle does not stop a task, it only detaches it. So you need a way to ask tasks to stop and a way to learn that they have.
Step 1: Detect the shutdown request
tokio::signal::ctrl_c() completes when the process receives Ctrl+C. It needs Tokio's signal feature (or full).
Step 2: Broadcast the request
A broadcast channel reaches many tasks at once. Each task subscribes and includes the receiver in a select!.
Step 3: Wait for tasks to finish
Keep the JoinHandles and await them after sending the signal.
use std::time::Duration;
use tokio::sync::broadcast;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let (shutdown_tx, _) = broadcast::channel::<()>(1);
let mut handles = Vec::new();
for id in 0..3 {
let mut shutdown_rx = shutdown_tx.subscribe();
handles.push(tokio::spawn(async move {
loop {
tokio::select! {
_ = shutdown_rx.recv() => {
println!("worker {id}: cleaning up");
break;
}
_ = sleep(Duration::from_millis(200)) => {
println!("worker {id}: tick");
}
}
}
}));
}
tokio::signal::ctrl_c().await.unwrap();
println!("shutdown requested");
let _ = shutdown_tx.send(());
for h in handles {
h.await.unwrap();
}
println!("all workers stopped");
}Each worker finishes the arm it is in, then sees the signal on the next loop pass. Work inside the sleep arm is never interrupted halfway, because select! only drops a branch while it is waiting.
Using channel closure as the signal
You can skip the dedicated channel. A worker reading from an mpsc receiver sees None once every sender is dropped, as in the earlier channel example. Dropping the sender, then awaiting the workers, drains queued messages first. This suits pipelines where you want pending work finished rather than abandoned.
Putting a limit on the wait
A stuck task would make shutdown hang forever. Wrap the wait in tokio::time::timeout:
use std::time::Duration;
use tokio::time::timeout;
async fn wait_all(handles: Vec<tokio::task::JoinHandle<()>>) {
let all = async {
for h in handles {
let _ = h.await;
}
};
if timeout(Duration::from_secs(5), all).await.is_err() {
eprintln!("some tasks did not stop in time");
}
}Common errors
- Forgetting to await the handles. The signal is sent, but
mainexits before workers clean up. - Holding the original sender. With the
mpscapproach, the receive loop never ends if any sender, including the one inmain, stays alive. - Blocking work in a worker. A task stuck in blocking code cannot see the signal. Move such code to
spawn_blocking, and note that the runtime waits for those threads when it drops. - Ignoring
JoinHandleerrors. A panicked worker returnsErr. Log it rather thanunwrapif you want the other workers to be awaited.
Exercise
Why does dropping a JoinHandle not stop a task, and what should you do instead to stop it?
Show answer
Dropping a JoinHandle only detaches it, so the task keeps running. To stop a task cooperatively, send it a shutdown signal (for example over a broadcast channel or by dropping an mpsc sender) and have it exit its loop. Then await its JoinHandle. You can also call abort() on the handle, but that cancels the task at its next await without cleanup.
Exercise
In the mpsc-based approach, the worker loop never ends even though all spawned producers finished. What is the most likely cause?
Show answer
A Sender is still alive, most often the original one in main that was never dropped. recv() returns None only after every Sender is dropped.