In Rust, why does moving an `Arc<mpsc::Receiver<u64>>` clone into `thread::spawn` fail with E0277, while `Arc<Mutex<Receiver<u64>>>` compiles?
answer
- what Arc clones let threads do
- Send for Arc needs two bounds
- Receiver is Send, not Sync
- Mutex turns Send into Sync
basics
~20 sArc<T> is Send only when T: Send + Sync, because its clones hand &T to many threads. mpsc::Receiver is Send but not Sync, so Arc<Receiver> is not Send; Mutex<T> is Sync whenever T: Send, which repairs it.
solid answer
~40 sstd declares `unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T>`. `Sync` is needed because every clone derefs to `&T`, so moving a clone to another thread means several threads hold `&T` at once. `Send` is needed because whichever clone is dropped last drops the `T`, on whatever thread that happens to be, and `Arc::try_unwrap` can return the `T` there. `mpsc::Receiver<T>` is `Send` but explicitly `!Sync`, so `Arc<Receiver<u64>>` fails the bound and rustc reports E0277: "`std::sync::mpsc::Receiver<u64>` cannot be shared between threads safely", with a note that this is "required for `Arc<...>` to implement `Send`". `Mutex<T>` is `Sync` when `T: Send` alone, because the lock hands `&mut T` to one thread at a time, so `Arc<Mutex<Receiver<u64>>>` is `Send`.
code
rust · 18 linesuse std::sync::{mpsc, Arc, Mutex};
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel::<u64>();
// Arc::new(rx) alone fails: Receiver is Send but not Sync.
let rx = Arc::new(Mutex::new(rx));
let mut workers = Vec::new();
for _ in 0..2 {
let rx = Arc::clone(&rx);
workers.push(thread::spawn(move || rx.lock().unwrap().recv().ok()));
}
tx.send(7).unwrap();
drop(tx);
for w in workers {
println!("{:?}", w.join().unwrap());
}
}go deeper
Remember that Arc shares but does not lock: Arc<Mutex<T>> is the usual pairing when threads must change or consume shared state.
Explain both of Arc's bounds, Sync because clones hand out &T and Send because the last clone drops T, and why Mutex<T> is Sync with only T: Send.
Trace an E0277 from a Sync failure up through Arc or & to the Send bound on spawn, and choose the smallest synchronising wrapper that fixes it.
Prefer designs where each thread owns its receiving end, such as a multi-consumer channel, over a shared lock around one Receiver; review Arc<Mutex<_>> shapes for contention.
## The error and where it comes from A common first attempt at a worker pool shares one `std::sync::mpsc::Receiver` between workers by wrapping it in `Arc` and moving a clone into each `thread::spawn` closure. rustc 1.99.1 rejects it: ```plaintext error[E0277]: `std::sync::mpsc::Receiver<u64>` cannot be shared between threads safely = help: the trait `Sync` is not implemented for `std::sync::mpsc::Receiver<u64>` = note: required for `Arc<std::sync::mpsc::Receiver<u64>>` to implement `Send` ``` The message is about **`Sync`** even though `thread::spawn` asks for **`Send`**. The note explains the hop: the closure captures an `Arc<Receiver<u64>>`, the closure must be `Send`, and `Arc` is `Send` only under a condition that involves `Sync`. ## Arc's two bounds The standard library writes the impls by hand (in `alloc/src/sync.rs`): ```rust unsafe impl<T: ?Sized + Sync + Send, A: Allocator + Send> Send for Arc<T, A> {} unsafe impl<T: ?Sized + Sync + Send, A: Allocator + Sync> Sync for Arc<T, A> {} ``` Each bound covers a real way the inner value crosses threads: - **`T: Sync`** — every clone of an `Arc<T>` derefs to `&T`. Moving one clone to another thread while the original stays behind puts `&T` on two threads at once, which is exactly what `Sync` permits. - **`T: Send`** — the reference count decides who drops `T`: whichever clone goes last runs `T`'s destructor on its own thread. `Arc::try_unwrap` and `Arc::into_inner` can also hand the owned `T` to whichever thread holds the last clone. Either way `T` may end its life on a thread other than the one that created it. The atomic reference count is what makes `Arc` itself safe to clone across threads; it says nothing about whether the *contents* may be shared. That is why `Arc<T>` does not make an unshareable `T` shareable. ## Why Receiver is Send but not Sync `std::sync::mpsc` declares: - `unsafe impl<T: Send> Send for Receiver<T>` — you may move the single receiving end to another thread. - `impl<T> !Sync for Receiver<T>` — the receiving end is not meant to be used through shared references from several threads at once. (By contrast `Sender<T>` is both `Send` and `Sync` for `T: Send`.) Multi-consumer channels, where several workers each own a receiving end, belong to the lesson on channels. ## Why Mutex repairs it `Mutex<T>`'s impls are deliberately weaker than `Arc`'s: | Type | `Send` when | `Sync` when | |---|---|---| | `Arc<T>` | `T: Send + Sync` | `T: Send + Sync` | | `Mutex<T>` | `T: Send` | `T: Send` | | `RwLock<T>` | `T: Send` | `T: Send + Sync` | | `&T` | `T: Sync` | `T: Sync` | | `&mut T` | `T: Send` | `T: Sync` | A `Mutex` gives out access to its `T` to **one thread at a time**, through a `MutexGuard`. Exclusive access passed from thread to thread is a series of transfers, so `T: Send` is enough for `Mutex<T>` to be `Sync`; std's doc comment says it outright: "it is not necessary for `T` to be `Sync` as `&T` is only made available to one thread at a time if `T` is not `Sync`". `RwLock<T>` needs `T: Sync` as well because several readers can hold `&T` at the same moment. So the chain becomes: 1. `Receiver<u64>` is `Send`. 2. Therefore `Mutex<Receiver<u64>>` is `Send` and `Sync`. 3. Therefore `Arc<Mutex<Receiver<u64>>>` is `Send`, and the closure that captures a clone is `Send`. Each worker then calls `rx.lock().unwrap().recv()`, and only one worker is inside `recv` at a time. ## Reading similar errors The same reasoning explains other cases: - `Arc<MutexGuard<'_, T>>` is not `Send`, because a guard is `Sync` (when `T: Sync`) but not `Send` — `Arc` needs both. - `&Receiver<T>` is not `Send`, because `&T: Send` requires `T: Sync`; `&mut Receiver<T>` *is* `Send`, because exclusive references only need `T: Send`. - A struct with an `Arc<Receiver<T>>` field inherits the problem: it is not `Send`, and every closure that captures it fails the same way. - If only one thread needs the value, move the value itself (here the `Receiver`) into that thread instead of sharing it. - When an E0277 names a `Sync` failure under a `Send` requirement, look for an `Arc` or a `&` in the captured type: that is where `Sync` entered. The practical rule: `Arc<T>` shares, it does not synchronise. When `T` is not `Sync`, put a `Mutex` (or another synchronising type) between the `Arc` and the value.
- Why is `T: Sync` alone not enough for `Arc<T>` to be `Send`?Because ownership of `T` can end up on another thread. The clone that is dropped last runs `T`'s destructor on its own thread, and `Arc::try_unwrap` or `Arc::into_inner` can return the owned `T` there. Both are transfers of `T`, which is what `Send` governs.
- Why does `RwLock<T>` need `T: Send + Sync` to be `Sync` when `Mutex<T>` needs only `T: Send`?An `RwLock` lets several readers hold `RwLockReadGuard`s at once, each dereferencing to `&T`, so `T` really is shared between threads and must be `Sync`. A `Mutex` only ever exposes `T` to one thread at a time, which is a sequence of transfers and needs only `Send`.
- Wrapping any value in Arc makes it safe to use from many threads.
- Arc is Send whenever T is Send, because the Arc is moved, not the T.
- Mutex<T> needs T: Sync, since threads share the Mutex.
- The E0277 must be a bug, because spawn asks for Send and the error says Sync.
- Receiver is not Send, so it can never be moved to a worker thread.