Sub topic 12
Sharing state across tasks
This chapter assumes you know Arc, Mutex and move closures from std threads, and that you can spawn tasks with tokio::spawn. Spawned tasks must be Send + 'static, so they cannot borrow local variables. To share data, give each task its own owning handle to it.
Arc plus Mutex
Arc<T> is a reference-counted pointer that can be cloned and sent between threads. Mutex<T> allows one task at a time to change the value. Together, Arc<Mutex<T>> is the standard way to share mutable state.
use std::sync::{Arc, Mutex};
#[tokio::main]
async fn main() {
let counter = Arc::new(Mutex::new(0u32));
let mut handles = Vec::new();
for _ in 0..10 {
let counter = Arc::clone(&counter);
handles.push(tokio::spawn(async move {
*counter.lock().unwrap() += 1;
}));
}
for h in handles {
h.await.unwrap();
}
println!("{}", *counter.lock().unwrap());
}Each loop iteration clones the Arc and moves the clone into its task. The program prints 10.
The std Mutex is fine here because the lock is held for one short statement and never across an .await.
Which mutex to use
Tokio also provides tokio::sync::Mutex. Its lock() is an async fn, so a task that waits for the lock yields to the runtime instead of blocking a worker thread.
| Situation | Use |
|---|---|
| Short, synchronous critical section | `std::sync::Mutex` |
| Guard must be held across an `.await` | `tokio::sync::Mutex` |
| Many reads, few writes | `std::sync::RwLock` or `tokio::sync::RwLock` |
The async mutex is slower than the std one, so don't use it by default. Choose it only when you must hold the lock while awaiting, for example while writing to a socket that the lock protects.
The guard-across-await error
A std MutexGuard is not Send. If you hold one across an .await, the future stops being Send, and tokio::spawn rejects it. The error mentions that the future "cannot be sent between threads safely".
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let data = Arc::new(Mutex::new(Vec::<u32>::new()));
let d = Arc::clone(&data);
tokio::spawn(async move {
{
let mut v = d.lock().unwrap();
v.push(1);
} // guard dropped here, before the await
sleep(Duration::from_millis(10)).await;
})
.await
.unwrap();
println!("{:?}", data.lock().unwrap());
}The inner block drops the guard before the .await. Dropping it early is usually better than switching to the async mutex.
A guard held across an .await can also deadlock when it is a Send type such as the async one: another task may wait on the lock while the holder is suspended. Keep critical sections small either way.
Another option: own the state in one task
Instead of locking, you can let a single task own the data and have other tasks send it messages through a channel. The previous chapter covered channels. This avoids lock contention and guard problems, and it suits state with many operations. Use a mutex for small, simple values such as counters or a cache map.
Exercise
A task locks a std Mutex, then calls .await on a network read while still holding the guard. What happens when you pass this task to tokio::spawn, and what are two ways to fix it?
Show answer
The code fails to compile, because the MutexGuard is not Send and so the future is not Send. Fix it by dropping the guard before the .await (scope it in a block), or by switching to tokio::sync::Mutex, whose guard can be held across an .await. Moving the state into one owner task behind a channel also works.