skip to content

A Rust chat server's handler locks a `std::sync::Mutex`, then awaits a broadcast; why does spawning it fail, and how do you fix it?

level: middleimportance: must knowfreq 80%

answer

  1. what the future stores
  2. unlocked on the locking thread
  3. MutexGuard is not Send
  4. end the guard's scope first
  5. clippy await_holding_lock

basics

~20 s

The handler's future stores every local that is alive at an .await, and std's MutexGuard is deliberately not Send, so the future is not Send and a multi-threaded spawn rejects it. Release the guard in an inner block before awaiting.

solid answer

~50 s

An `async fn` compiles to a state machine that keeps each local still in scope at an `.await`. `let mut map = rooms.lock().unwrap();` creates a `std::sync::MutexGuard`, and std declares `impl !Send for MutexGuard` because pthreads require a mutex to be unlocked by the thread that locked it. With the guard alive at `broadcast(msg).await`, the whole future is not `Send`, so a spawn that requires `Send` fails with "future cannot be sent between threads safely" and a note that the guard "is used across an await". The fix is to put the locking in an inner block (or a plain sync helper) so the guard's scope ends before the `.await`; in rustc 1.99.1 a `drop(map)` after the mutation still fails, because `map.entry(..)` borrowed the guard through `DerefMut` and a borrowed local stays stored until its scope ends. If the critical section truly must span an await, use an async-aware mutex such as `futures::lock::Mutex`.

code

rust · 19 lines
rust
use futures::executor::ThreadPool;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

type Rooms = Arc<Mutex<HashMap<u32, Vec<String>>>>;

async fn broadcast(msg: String) { let _ = msg; }

async fn handle(rooms: Rooms, room: u32, msg: String) {
    let mut map = rooms.lock().unwrap();
    map.entry(room).or_default().push(msg.clone());
    broadcast(msg).await; // map, a MutexGuard, is still alive here
}

fn main() {
    let pool = ThreadPool::new().unwrap();
    let rooms: Rooms = Arc::new(Mutex::new(HashMap::new()));
    pool.spawn_ok(handle(rooms, 1, "hi all".into()));
}

go deeper

for a junior

Remember the rule of thumb: lock, do the synchronous work, let the guard go, then await. Know that the std MutexGuard is not Send.

for a middle

Explain that the future stores locals alive at each await, that one non-Send field makes the future non-Send, and why std makes the guard non-Send, then fix it with an inner block.

for a senior

Read the diagnostic's notes to the exact guard and await, know that drop() of a guard already used still fails in current rustc, and explain the same-thread deadlock that makes the pattern wrong even where it compiles.

for a principal

Turn it into a team default: std locks only for short synchronous sections, clippy's await_holding_lock kept on, and an async mutex reserved for the rare section that has to await.

## The handler that stopped building A chat server keeps its room history in an `Arc<Mutex<HashMap<u32, Vec<String>>>>`. After a refactor, the connection handler appends the message under the lock and then awaits a broadcast to the other members, all in one scope. Spawning that handler onto a multi-threaded executor such as futures' `ThreadPool` no longer compiles, although nothing in the body looks thread-unsafe: the map is behind an `Arc<Mutex<..>>`, the message is an owned `String`, and the same code worked when the broadcast happened before the lock. ## Why the guard ends up inside the future An `async fn` does not run when called. It returns an anonymous **future** type, a state machine with one state per `.await` point. Each state must store everything the code after that point may still use, which in practice means every local whose scope spans the `.await`. `rooms.lock().unwrap()` returns a `std::sync::MutexGuard<'_, HashMap<..>>`; bound to `map`, it is in scope at `broadcast(msg).await`, so the guard becomes a field of the future. `Send` is an auto trait, so the future is `Send` only if every stored field is. One non-`Send` field poisons the whole type, and the `Send` bound on the spawn function then fails. ## Why MutexGuard is not Send The std source states the reason in its doc comment: a `MutexGuard` "is not `Send` to maximize platform portability", because on platforms using POSIX threads a mutex must be released on the thread that acquired it. Dropping the guard unlocks the mutex, so moving the guard to another thread would move the unlock there too. The impl is a plain `impl<T: ?Sized> !Send for MutexGuard<'_, T>`; the guard is `Sync` when `T: Sync`, which does not help here. ## Reading the diagnostic rustc 1.99.1 prints this as `error: future cannot be sent between threads safely`, without an E-code, and the notes tell you exactly where to look: 1. "future returned by `handle` is not `Send`" names the async fn. 2. The `help` line names the culprit type, `std::sync::MutexGuard<'_, ...>`. 3. "future is not `Send` as this value is used across an await" points at the `let` that created the guard and the `.await` it spans, adding "with `mut map` maybe used later". 4. "required by a bound in `ThreadPool::spawn_ok`" shows which `Send` bound demanded it. ## The fixes | fix | when it fits | cost | |---|---|---| | inner block `{ let mut map = ...; ... }` before the `.await` | the critical section has no await in it | none; this is the default | | sync helper `fn record(rooms: &Mutex<..>, ..)` called before the `.await` | the locked work is more than a line | none; the guard never meets an await | | copy out what you need (`.clone()`, a count) inside the block, then await | later code needs data read under the lock | a clone | | async-aware mutex, `futures::lock::Mutex` | the lock must really be held across the await | slower lock, and `lock()` is itself a future | Things that look like fixes but are not: - **`drop(map)` before the `.await`.** `map.entry(..)` borrowed the guard through `DerefMut`, and once a local has been borrowed rustc 1.99.1 keeps its storage in the future until its scope ends, so the same error appears despite the `drop`. Use a block. - **Switching to `parking_lot::Mutex`.** Its guard is also not `Send` unless the crate's `send_guard` feature is enabled, and even then a blocking lock held across an await stays a bad idea. - **Making the executor single-threaded.** That changes which spawn you call; it does not make holding a blocking lock across an await safe. ## Why the error is doing you a favour Even where it compiles, for example on a local executor, holding a `std::sync::Mutex` across an `.await` is a bug waiting to happen. While the task is suspended the lock stays taken; another task on the same worker that calls `lock()` blocks the thread, and the suspended holder can never be polled to release it, so the thread deadlocks. Clippy's `await_holding_lock` lint, in the `suspicious` group and warn by default, flags the pattern even when no `Send` bound is involved. Lock, do synchronous work, unlock, then await.

  • Why doesn't calling `drop(map)` right before the `.await` make the handler's future `Send`?
    `map.entry(..)` borrowed the guard through `DerefMut`. Once a local has been borrowed, rustc 1.99.1 cannot prove no reference to it survives, so it keeps the local's storage in the future until its scope ends, even after `drop` moved the guard out; the error repeats, saying the await occurs "with `mut map` maybe used later". Ending the scope with an inner block, or doing the locked work in a sync helper, is what the compiler recognises.
  • When is an async-aware mutex the right fix instead of shortening the critical section?
    When the protected operation must itself await, such as writing a framed message to a shared connection without interleaving. `futures::lock::Mutex` hands out a guard that is `Send` when `T: Send`, and contended `lock()` suspends the task instead of blocking the thread. It is slower than `std::sync::Mutex`, so keep std's mutex for short synchronous sections.
  • If the handler runs on a single-threaded local executor, is holding the std guard across `.await` fine?
    It compiles, because nothing asks for `Send`, but it can deadlock: while the holder is suspended, another task on the same thread that calls `lock()` blocks the only thread, so the holder is never polled again to release the lock. Clippy's `await_holding_lock` warns about it for exactly this reason.

  • Calling drop(guard) after using it, before the .await, is enough for rustc to accept it.
  • The error means HashMap is not thread-safe.
  • MutexGuard is not Send because Mutex itself is not Sync.
  • Running on a single-threaded executor makes holding the lock across .await safe.
  • Swapping in parking_lot::Mutex fixes it without any other change.