Why is Rust's `std::sync::MutexGuard` never `Send`, though a `&MutexGuard<T>` may cross threads when `T: Sync`, and what does that rule out?
answer
- who must release the lock
- a POSIX threads requirement
- a negative impl in std
- Deref gives &T, so Sync needs T: Sync
basics
~20 sstd writes impl !Send for MutexGuard because some platforms, POSIX threads among them, require a mutex to be unlocked by the thread that locked it. The guard is Sync when T: Sync, since &MutexGuard only yields &T.
solid answer
~50 sA `MutexGuard` unlocks its mutex when it is dropped, so wherever the guard goes, the unlock goes. std's source says the guard is not `Send` "to maximize platform portability": on platforms that use POSIX threads a lock must be released on the thread that acquired it, so `impl<T: ?Sized> !Send for MutexGuard<'_, T>` stops it from being dropped elsewhere. Sharing is different: `&MutexGuard<T>` derefs only to `&T`, so std writes `unsafe impl<T: ?Sized + Sync> Sync for MutexGuard<'_, T>`. In practice you cannot move a locked guard into a spawned or scoped thread (E0277 "cannot be sent between threads safely"), cannot hand a lock from one thread to another, and cannot put a guard in an `Arc`; you can lend `&guard` to a scoped thread, or take the data out and send that instead. The `RwLock` guards follow the same rule.
code
rust · 14 linesuse std::sync::Mutex;
use std::thread;
static TOTALS: Mutex<Vec<u64>> = Mutex::new(Vec::new());
fn main() {
let guard = TOTALS.lock().unwrap();
thread::scope(|s| {
s.spawn(move || {
let mut g = guard; // move the locked guard into another thread
g.push(1);
});
});
}go deeper
Recall that a MutexGuard unlocks on drop and cannot be moved into another thread; let each thread lock the Mutex itself.
Explain the negative impl and its POSIX threads reason, and why the guard is still Sync when T: Sync because Deref only gives &T.
Recognise designs that try to hand a lock between threads, rewrite them to move data or lock locally, and know the RwLock guards share the rule.
When evaluating a lock crate whose guards can be made Send, weigh that flexibility against features it disables, such as parking_lot's deadlock detection.
## What the guard represents `Mutex::lock` returns a `MutexGuard<'_, T>`, an **RAII** handle: while it lives, the mutex is held and the guard dereferences to the protected `T`; when it is dropped, the mutex is unlocked. The guard is therefore not just a pointer to data — it *is* the held lock, and its destructor is the unlock call. That makes the question "may this value move to another thread?" the same as "may the lock be released by a different thread than the one that took it?" ## What std's source says The standard library answers in `std/src/sync/poison/mutex.rs`: - `impl<T: ?Sized> !Send for MutexGuard<'_, T> {}` — documented as: "A `MutexGuard` is not `Send` to maximize platform portability. On platforms that use POSIX threads (commonly referred to as pthreads) there is a requirement to release mutex locks on the same thread they were acquired." - `unsafe impl<T: ?Sized + Sync> Sync for MutexGuard<'_, T> {}` — documented as: `T` must be `Sync` "because it is possible to get a `&T` from `&MutexGuard` (via `Deref`)". Note the scope of the reason: it is about portability to platforms with that requirement, not a claim that every platform misbehaves. std chooses the rule that is correct everywhere, so Rust code that compiles on one platform does not become unsound on another. The same pattern appears on `MappedMutexGuard` and on all four `RwLock` guard types (`RwLockReadGuard`, `RwLockWriteGuard` and their mapped forms): each is `!Send` and `Sync` when `T: Sync`. ## What the rule rules out Because the guard is not `Send`, rustc rejects any construct that would carry it to another thread: 1. **Moving a locked guard into a worker.** Even inside `thread::scope`, where no `'static` bound applies, a `move` closure that captures the guard fails with E0277: "`std::sync::MutexGuard<'_, Vec<u64>>` cannot be sent between threads safely", pointing at the `F: FnOnce() -> T + Send + 'scope` bound on `Scope::spawn`. 2. **Handing a lock over.** Patterns such as "thread A locks, sends the guard down a channel, thread B unlocks" cannot be expressed; `mpsc::Sender<MutexGuard<_>>` would need the guard to be `Send`. 3. **Sharing a guard through `Arc`.** `Arc<T>` is `Send` only when `T: Send + Sync`, and the guard fails the `Send` half. 4. **Returning a guard from a spawned thread.** `thread::spawn` requires the closure's return type to be `Send`. Holding a guard across an `.await` in an async function, which makes the future non-`Send`, is the same rule seen from the async side and is covered in the lesson on `Send` futures. ## What still works The `Sync` impl leaves useful room: - **Lending the guard.** A scoped thread may borrow `&guard` and read through it, because `&MutexGuard<Vec<u64>>` is `Send` when `Vec<u64>: Sync`. The lock is still released by the owning thread when it drops the guard. - **Moving the data, not the lock.** Lock, `std::mem::take` the contents out of the guard, drop the guard, then send the owned data to another thread. - **Locking where you use it.** Share the `Mutex` (through `Arc` or a reference) and let each thread call `lock` itself, so every guard lives and dies on one thread. | Want | Allowed? | Why | |---|---|---| | move `MutexGuard` to another thread | no | `!Send` | | lend `&MutexGuard<T>` to a scoped thread | yes, if `T: Sync` | guard is `Sync` | | move the `Mutex<T>` or share `&Mutex<T>` | yes, if `T: Send` | `Mutex<T>` is `Send` and `Sync` | | send the owned `T` after unlocking | yes, if `T: Send` | ordinary transfer | ## Diagnosing it in review - The E0277 names `MutexGuard` beside a `Send` bound on `thread::spawn`, `Scope::spawn` or a channel's `send`; the fix is never an impl on the guard, since your crate cannot add a `Send` impl to a std type. - A guard stored in a struct field makes that struct `!Send` as well, so a long-lived "locked session" object cannot move between threads. - When a design really needs the right to use some data to travel between threads, model it with data — the value itself, or a message on a channel — rather than with a guard. ## Outside std parking_lot's guards are also `!Send` by default; its lock_api layer encodes this with a `GuardNoSend(*mut ())` marker. The crate offers a `send_guard` feature that makes them `Send`, and it refuses to compile together with its `deadlock_detection` feature. Whether to adopt parking_lot at all is a question for the lesson on locks.
- Why does `MutexGuard<T>`'s `Sync` impl require `T: Sync` rather than `T: Send`?Because sharing the guard means several threads hold `&MutexGuard<T>`, and each can deref it to `&T` at the same time. That is shared access to `T`, which needs `T: Sync`. `Mutex<T>` itself needs only `T: Send` because it hands out `T` to one thread at a time.
- A worker needs to process data that the main thread has locked; what do you do instead of sending the guard?Either lend `&guard` to a scoped thread while the main thread keeps the lock, or take the data out with `std::mem::take(&mut *guard)`, drop the guard, and move the owned value to the worker. If the worker should hold the lock itself, share the `Mutex` and let it call `lock`.
A MutexGuard is like a cloakroom ticket that only the issuing desk can redeem: you may show the ticket to others so they can read it, but the coat must come back to the same desk that took it.
- MutexGuard is not Send because sending it would create two &mut T.
- A guard is not Sync either, since it is not Send.
- Wrapping the guard in Arc lets another thread use it.
- thread::scope removes the Send requirement because the threads borrow.
- Every platform corrupts a mutex unlocked from another thread.