
Understand it
A useful shutdown sequence has three responsibilities: decide that shutdown is needed, notify the components that own work, and wait for their completion. Before signaling workers, stop accepting new work so the system cannot refill its queue forever. Then decide whether already accepted work is drained, rejected with an explicit result, or interrupted at a documented safe point.
The example uses a watch channel carrying a persistent boolean state. Each worker subscribes before the request and observes the current value before waiting for a change. That first check matters: a worker that starts after the value became true must not wait forever for another update. A watch channel represents the latest state, not a queue containing one shutdown message per worker.
After sending the request, the owner drains JoinSet and confirms that both workers acknowledged shutdown. This is deliberately an in-memory example without operating-system signals. A desktop service can translate ctrl-c into the same protocol, while a UI can translate an explicit Cancel action. The cancellation source and the worker contract remain separate so the protocol can be tested without terminating the process.
A real service also needs a deadline and escalation policy for stuck workers. Aborting a task is not a substitute for safe cancellation of a transaction or a blocking operation. Keep partial progress visible, release permits with RAII, and do not report that a save completed merely because the worker future was dropped. Test shutdown requested before subscription, during idle work, and after completion.
Local Cargo profile: open the supplied project in Crabrix or the browser Playground. Explicitly prepare its pinned Cargo packages once on each device, then Run and Debug compile and execute on that device without a backend. The project includes Cargo.lock. The lesson question remains the completion exercise; running an unchanged demonstration does not prove a separate programming challenge. Tokio 1.54.1 is built with default-features=false and only rt/sync. The current-thread builder needs no runtime attribute macro. JoinSet, Semaphore, watch and yield_now are real Tokio APIs. This profile supplies cooperative concurrency, not native threads, sockets, OS signals or CPU parallelism.
Read the code
use tokio::{
runtime::Builder, sync::watch, task::JoinSet,
};
fn main() {
Builder::new_current_thread()
.build()
.unwrap()
.block_on(async {
let (stop, receiver) =
watch::channel(false);
let mut tasks = JoinSet::new();
for _ in 0..2 {
let mut rx = receiver.clone();
tasks.spawn(async move {
loop {
if *rx.borrow() {
break;
}
if rx
.changed()
.await
.is_err()
{
break;
}
}
"stopped"
});
}
stop.send(true).unwrap();
let mut stopped = 0;
while let Some(result) =
tasks.join_next().await
{
assert_eq!(
result.unwrap(),
"stopped"
);
stopped += 1;
}
assert_eq!(stopped, 2);
});
println!("graceful-shutdown-protocol: ok");
}
Stop admission, signal, and wait
Try it
Run the declared desktop Cargo example. Request shutdown before spawning a late worker and verify it observes the current state immediately. Open the supplied local Cargo project, prepare packages, then Run or Debug it. Change inputs and examine the assertions. Answer the lesson question separately.
What success looks like: Shutdown is persistent state. A late subscriber must inspect the current value instead of waiting for a future change that may never arrive.
Check your understanding
Why check the current watch value before awaiting changed()?
Reveal the answer
- It provides CPU parallelism
- It prevents shutdown requested earlier from being missed by a late worker
- It serializes every file on the server
Shutdown is persistent state. A late subscriber must inspect the current value instead of waiting for a future change that may never arrive.
Go deeper
Common misconception: Sending a stop signal proves that every worker has finished.
The owner must also observe task completion, and define a policy for workers that do not cooperate.
- Stop admission: Prevent new accepted jobs while shutdown is underway.
- Notify: Publish persistent shutdown state to each worker.
- Wait: Join every worker and handle failures before reporting completion.
Transfer challenge: Write down a deadline and escalation policy for a worker that never reaches a cancellation point. Label which steps require timer or host support outside this rt/sync profile.
Connections
- Bound Work Before Spawning: Semaphore permits and bounded queues