Fix an async function that holds a std::sync::MutexGuard across .await
record adds a value to a shared buffer and, once 100 values have piled up, sends them as one batch with flush. Each call runs as its own task: tokio::spawn(record(Arc::clone(&stats), v)). That line does not compile: error: future cannot be sent between threads safely, with the note future is not `Send` as this value is used across an await. Explain what the compiler objects to and what would go wrong at run time even if it accepted the code, then rewrite record.
Requirements:
- Keep the signature and keep
std::sync::Mutex. - Every value ends up in exactly one batch: none is lost or sent twice.
use std::sync::{Arc, Mutex};
async fn flush(batch: &[u32]) {
println!("sending {} values", batch.len()); // a network call
}
async fn record(stats: Arc<Mutex<Vec<u32>>>, v: u32) {
let mut g = stats.lock().unwrap();
g.push(v);
if g.len() >= 100 {
flush(&g).await;
g.clear();
}
}Find and fix the bug.
MutexGuard is not Send, so tokio::spawn rejects a future holding it across .await, and a task asleep with the lock stalls others, even deadlocks. Take the batch out in a block, then await; use tokio::sync::Mutex only across awaits.
- Expecting
drop(guard)before.awaitto make the futureSendagain in rustc 1.99 - Reaching for
tokio::sync::Mutexby default, though it is slower and needed only across an await - Overlooking the deadlock when a task suspends holding a
stdlock on a single-threaded runtime
- Why does an
Rcor aRefCellborrow held across.awaitcause the same error? - How would a message-passing actor task that owns the buffer replace the lock here?
The compiler objects to the guard g being alive at flush(&g).await. MutexGuard is not Send: an OS lock is released on the thread that took it. A multi-threaded runtime may move a task from tokio::spawn to another thread at any .await, so spawn requires Future: Send, and a Future stores everything that lives across an await point. Even without the check the code would be bad: the task would sleep holding the lock for the whole network call, other record calls would block their worker threads on lock(), and on a single-threaded runtime the thread waiting for the lock would never let the first task wake up and release it — a deadlock.
The fix is to take the batch out under the lock and send it with the lock already released. The code below is built with rustc 1.99 without Tokio: spawn_like carries the same Send + 'static bound as tokio::spawn, and a simple block_on stands in for the runtime.
use std::future::Future;
use std::pin::pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
fn block_on<F: Future>(fut: F) -> F::Output {
let mut fut = pin!(fut);
let mut cx = Context::from_waker(Waker::noop());
loop {
if let Poll::Ready(v) = fut.as_mut().poll(&mut cx) {
return v;
}
}
}
// the same bound as tokio::spawn
fn spawn_like<F: Future + Send + 'static>(fut: F) -> F {
fut
}
async fn flush(batch: &[u32]) {
println!("sending {} values", batch.len());
}
async fn record(stats: Arc<Mutex<Vec<u32>>>, v: u32) {
let batch = {
let mut g = stats.lock().unwrap();
g.push(v);
if g.len() < 100 {
return;
}
std::mem::take(&mut *g) // the buffer is empty, new values go into the next batch
}; // the guard is dropped here, before any .await
flush(&batch).await;
}
fn main() {
let stats = Arc::new(Mutex::new(Vec::new()));
for v in 0..250 {
block_on(spawn_like(record(Arc::clone(&stats), v)));
}
println!("left {}", stats.lock().unwrap().len()); // sending 100 values (×2), left 50
}The separate block is required: in rustc 1.99, drop(g) before the .await does not remove the error — the analysis looks at the variable's scope, not at the drop call. std::mem::take swaps in an empty vector, so values arriving while a batch is being sent pile up for the next batch. tokio::sync::Mutex is needed only when the lock is meant to be held across an .await — for example, to serialize writes to one connection; it is slower, and a short critical section is fine with std::sync::Mutex.