Sub topic 3
Sharing State Across Tokio Tasks
This chapter assumes Rust ownership, borrowing, lifetimes, traits, closures, Cargo, and basic Arc/Mutex use. It focuses on the choices that keep concurrent Tokio programs safe and responsive.
Sharing state across tasks
A Tokio task may run on a different worker thread, so shared data must be thread-safe. Arc<T> gives shared ownership. Mutex<T> allows one task to change the protected value at a time.
Use std::sync::Mutex when the critical section is short and contains no .await. Use tokio::sync::Mutex when the lock must remain held across an asynchronous wait.
use std::sync::{Arc, Mutex};
#[tokio::main]
async fn main() {
let count = Arc::new(Mutex::new(0u32));
let mut tasks = Vec::new();
for _ in 0..10 {
let count = Arc::clone(&count);
tasks.push(tokio::spawn(async move {
*count.lock().unwrap() += 1;
}));
}
for task in tasks {
task.await.unwrap();
}
println!("{}", *count.lock().unwrap());
}Never hold a blocking mutex guard across .await. It can block a runtime worker and delay unrelated tasks.
Keeping the runtime responsive: `spawn_blocking`
CPU-heavy work and blocking library calls do not yield to Tokio. Run them with spawn_blocking, which uses a separate thread pool.
#[tokio::main]
async fn main() {
let total = tokio::task::spawn_blocking(|| {
(1..=1_000_000u64).sum::<u64>()
})
.await
.unwrap();
println!("{total}");
}Cancellation and cancel safety
Dropping a future cancels its unfinished operation. Cancellation is cancel safe when dropping it does not lose or corrupt state. Tokio channel receives and many I/O operations are designed for this, but an application protocol may need explicit cleanup.
flowchart TD
A[Run task] --> B{Shutdown signal?}
B -- no --> C[Handle I/O]
C --> B
B -- yes --> D[Drop or abort tasks]
D --> E[Await task cleanup]Shutting down cleanly
A service should stop accepting work, notify existing tasks, await their completion, and release resources. A watch channel is useful for broadcasting shutdown.
Putting it together: a concurrent TCP echo server
Each connection gets its own task. The JoinSet lets the server track those tasks during shutdown.
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpListener,
task::JoinSet,
};
#[tokio::main]
async fn main() -> std::io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
let mut clients = JoinSet::new();
loop {
tokio::select! {
result = listener.accept() => {
let (mut socket, _) = result?;
clients.spawn(async move {
let mut buffer = [0; 1024];
loop {
let n = socket.read(&mut buffer).await?;
if n == 0 { return Ok(()); }
socket.write_all(&buffer[..n]).await?;
}
});
}
_ = tokio::signal::ctrl_c() => break,
}
}
while clients.join_next().await.is_some() {}
Ok(())
}Testing async code
Use #[tokio::test] to create a runtime for a test. Test behavior through public operations, such as sending a message and checking the result.
#[tokio::test]
async fn doubles_a_number() {
async fn double(value: u32) -> u32 {
value * 2
}
assert_eq!(double(21).await, 42);
}Exercise
Why should a CPU-heavy calculation use spawn_blocking?
Show answer
It runs on Tokio's blocking thread pool instead of occupying an async worker thread.