Sub topic 12
Sharing state across tasks
This chapter assumes you know Rust ownership and borrowing, Arc and Mutex from std, and how tokio::spawn works, including why spawned futures must be Send + 'static. By the end you should be able to pick between a std mutex, a Tokio mutex, an RwLock, atomics, and message passing, and avoid the common errors.
Why sharing needs `Arc`
A spawned task must be 'static, so it cannot borrow a local variable from the function that spawned it. Several tasks that need the same value must each own a handle to it. Arc<T> is that handle. It is an atomically reference-counted pointer, and cloning it only bumps a counter.
Arc gives shared ownership but only shared (read-only) access. To mutate the value you need interior mutability inside the Arc. For Arc<T> to be Send, the inner T must be Send + Sync. A Mutex<T> is Sync whenever T is Send, so Arc<Mutex<T>> satisfies the bound for most data. Rc<RefCell<T>> does not, and the compiler rejects it in tokio::spawn.
The basic pattern: `Arc<Mutex<T>>`
The standard library mutex is the right default for short critical sections.
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 shadows counter with a clone, and async move moves that clone into the task. The guard returned by lock() is a temporary dropped at the end of the statement, so the lock is held for one increment only. The program prints 10.
The .await on each handle happens in a different statement from any lock, which matters for the next section.
Never hold a `std` guard across `.await`
A std::sync::MutexGuard is not Send. If it lives across an .await, the future that contains it is not Send either, and tokio::spawn refuses to compile it. This is often the first error people hit.
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 guard = d.lock().unwrap();
guard.push(1);
} // guard dropped here, before the await
sleep(Duration::from_millis(10)).await;
d.lock().unwrap().push(2);
})
.await
.unwrap();
println!("{:?}", data.lock().unwrap());
}The inner block ends the guard's life before sleep(...).await. Calling drop(guard) also works for the compiler in recent Rust versions, but a block scope is the most reliable way to make the intent clear.
Even where the compiler accepts it, holding a std lock across an await can deadlock. Task A takes the lock and suspends. Task B, running on the same worker thread, calls lock() and blocks the whole thread. Task A can never resume to release the lock.
When to use `tokio::sync::Mutex`
tokio::sync::Mutex has an async lock(). A task waiting for it yields to the scheduler instead of blocking a thread, and its guard is Send, so it can be held across .await.
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let log = Arc::new(Mutex::new(Vec::<String>::new()));
let mut handles = Vec::new();
for i in 0..3 {
let log = Arc::clone(&log);
handles.push(tokio::spawn(async move {
let mut guard = log.lock().await;
guard.push(format!("start {i}"));
sleep(Duration::from_millis(20)).await; // lock held across await
guard.push(format!("end {i}"));
}));
}
for h in handles {
h.await.unwrap();
}
for line in log.lock().await.iter() {
println!("{line}");
}
}Each task's start and end lines stay adjacent, because the lock is held for the whole sleep. The cost is that the async mutex is slower than the std one, and the other tasks wait for the full 20 ms.
The Tokio documentation recommends this rule of thumb:
| Situation | Use |
|---|---|
| Short, synchronous critical section (no `.await` inside) | `std::sync::Mutex` (or `parking_lot`) |
| Lock must be held across an `.await` | `tokio::sync::Mutex` |
| Many readers, rare writers | `RwLock` (`std` or Tokio, same rule as above) |
| A single counter or flag | Atomics |
| One task owns the resource, others make requests | Message passing |
Using the Tokio mutex everywhere "to be safe" is a common mistake. Most of the time the std mutex is faster and just as correct.
Lock poisoning
If a task panics while holding a std mutex guard, the mutex is marked poisoned. Later lock() calls return Err. Calling .unwrap() then panics in every other task that touches the lock, which spreads the failure. You can recover the data with lock().unwrap_or_else(|e| e.into_inner()) when the data is still valid. tokio::sync::Mutex does not poison.
Atomics for simple values
For a counter or a flag, a lock is more than you need. Atomics need no guard and never block.
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
#[tokio::main]
async fn main() {
let hits = Arc::new(AtomicUsize::new(0));
let mut handles = Vec::new();
for _ in 0..100 {
let hits = Arc::clone(&hits);
handles.push(tokio::spawn(async move {
hits.fetch_add(1, Ordering::Relaxed);
}));
}
for h in handles {
h.await.unwrap();
}
println!("{}", hits.load(Ordering::Relaxed));
}Ordering::Relaxed is enough for an independent counter. If the atomic guards other data, such as a "ready" flag, you need Release on the store and Acquire on the load.
Read-heavy state with `RwLock`
An RwLock allows many simultaneous readers or one writer. It pays off when reads dominate and the critical section is long enough to make contention matter. For tiny critical sections a plain mutex is often just as fast. Tokio's RwLock is fair: a waiting writer blocks new readers, so writers are not starved. The std RwLock makes no such promise across platforms.
Do not take a read lock and then try to take a write lock on the same lock from the same task. It deadlocks, because the write waits for the read guard you still hold.
Sharing by messaging instead
Locks are not the only option. The alternative is to give one task sole ownership of the state and let others talk to it through channels. This is sometimes called the actor pattern. Because only one task touches the data, no lock is needed, and you can hold the state across .await freely.
use std::collections::HashMap;
use tokio::sync::{mpsc, oneshot};
enum Command {
Set(String, u32),
Get(String, oneshot::Sender<Option<u32>>),
}
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<Command>(32);
let owner = tokio::spawn(async move {
let mut map: HashMap<String, u32> = HashMap::new();
while let Some(cmd) = rx.recv().await {
match cmd {
Command::Set(k, v) => {
map.insert(k, v);
}
Command::Get(k, reply) => {
let _ = reply.send(map.get(&k).copied());
}
}
}
});
tx.send(Command::Set("a".into(), 7)).await.unwrap();
let (reply_tx, reply_rx) = oneshot::channel();
tx.send(Command::Get("a".into(), reply_tx)).await.unwrap();
println!("a = {:?}", reply_rx.await.unwrap());
drop(tx);
owner.await.unwrap();
}The oneshot channel carries the reply back to the caller. When tx is dropped, recv() returns None and the owner task exits.
The trade-off is an extra hop and a bounded queue. Callers wait if the channel is full, and you must define a message type. In return you get one place where state changes happen, which is easier to reason about than many scattered lock() calls.
Common errors
- "future cannot be sent between threads safely". A
stdguard, anRc, or aRefCellborrow lives across an.await. Shorten the guard's scope or switch to an async mutex. - Cloning the data instead of the
Arc.Arc::clone(&x)shares. Cloning the inner value makes a copy that nobody else sees. - Using the wrong clone name. Writing
let counter = counter.clone();is fine, but callingcounter.lock()on the outer variable inside a loop after moving it gives "value moved". Make the clone inside the loop body, beforeasync move. - Holding a lock while doing slow work. Copy the data you need out of the guard, release it, and then do the work.
- Lock ordering deadlocks. If task A locks X then Y while task B locks Y then X, both can wait forever. Always lock in the same order, or combine the two values under one lock.
- Blocking
lock()on a contendedstdmutex in a hot async path. A short hold is fine. A long hold stalls the worker thread and every task scheduled on it.
Exercises
Exercise
A task does let g = std_mutex.lock().unwrap(); do_io(&g).await; and is passed to tokio::spawn. What goes wrong, and give two ways to fix it?
Show answer
The MutexGuard is held across an .await, so the future is not Send and the code does not compile (and could deadlock a worker thread if it did). Fix it by either (1) copying what you need out of the guard and dropping it before the .await, using a block scope, or (2) switching to tokio::sync::Mutex and using .lock().await, whose guard is Send.
Exercise
You have a request counter incremented by hundreds of tasks and read occasionally for metrics. Which primitive fits best, and why?
Show answer
An AtomicU64 (or AtomicUsize) inside an Arc, using fetch_add with Ordering::Relaxed. The value is one integer with no relation to other data, so a lock adds cost and contention for no benefit.
Exercise
Why might you choose an owner task with an mpsc channel over Arc<Mutex<HashMap<..>>> when each update needs to call an async database before writing to the map?
Show answer
The owner task can hold the map and .await the database call without any lock, so there is no guard to hold across an await and no lock contention. The cost is a message type, a reply channel, and one extra hop per operation.