In Rust, why can't four worker threads share one std::sync::mpsc::Receiver, and when would you switch to crossbeam-channel instead?
answer
- single consumer, enforced by types
- Receiver: no Clone, not Sync
- Arc needs Sync for Send
- MPMC, select!, timers
basics
~20 sstd's Receiver is not Clone and not Sync, so it cannot be shared and Arc<Receiver> fails with E0277. Use Arc<Mutex<Receiver>> for a std-only fix, or crossbeam-channel, whose Receiver is Clone and which adds select! over several channels.
solid answer
~30 s`std::sync::mpsc` is single-consumer by type: `Receiver<T>` has no `Clone` and is `!Sync`, so moving it into a second closure is E0382 and `Arc<Receiver<T>>` fails `thread::spawn`'s `Send` bound with E0277, "cannot be shared between threads safely". The std-only workaround is `Arc<Mutex<Receiver<T>>>`, locking only around `recv`, which serialises waiting. `crossbeam_channel` gives multi-consumer channels: its `Receiver` is `Clone` and `Sync`, each message goes to one receiver, and `select!` waits on several channels with timeouts and `tick` timers. Since Rust 1.67 std's channel is built on crossbeam's code, so switch for features, several consumers or `select!`, rather than speed.
code
rust · 20 linesuse std::sync::{Arc, mpsc};
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel::<String>();
let rx = Arc::new(rx);
let mut workers = Vec::new();
for _ in 0..4 {
let rx = Arc::clone(&rx);
workers.push(thread::spawn(move || {
for job in rx.iter() {
println!("encode {job}");
}
}));
}
drop(tx);
for w in workers {
w.join().unwrap();
}
}go deeper
Recall that the standard channel has one Receiver that cannot be cloned, so only one thread receives.
Explain the E0277 from Arc<Receiver>, and how Arc<Mutex<Receiver>> works around it at the cost of serialised waiting.
Show you know crossbeam's MPMC Receiver, select! with random choice, disconnected arms that spin, and when the Mutex wrapper is still enough.
Weigh a new dependency against std, given std's channel already uses crossbeam's design; switch for multiple consumers or select!, not speed.
## The standard channel has exactly one consumer The `mpsc` in `std::sync::mpsc` means multi-producer, **single-consumer**, and the type system enforces the single consumer: - `Sender<T>` and `SyncSender<T>` implement `Clone`; **`Receiver<T>` does not**, so there is no `rx.clone()` to hand each worker its own handle. - `Receiver<T>` is `Send` (when `T: Send`), so it can be **moved** to one other thread, but std declares `impl<T> !Sync for Receiver<T>`, so it cannot be **shared** by reference between threads. - Moving the one `Receiver` into the first worker's closure leaves nothing for the second: the next iteration fails with E0382, use of moved value. Wrapping it in an `Arc` does not help. `Arc<T>` is only `Send` when `T` is both `Send` and `Sync` (the lesson on `Send` and `Sync` covers why), so `thread::spawn` rejects the closure with E0277: ```plaintext error[E0277]: `std::sync::mpsc::Receiver<String>` cannot be shared between threads safely = help: the trait `Sync` is not implemented for `std::sync::mpsc::Receiver<String>` = note: required for `Arc<std::sync::mpsc::Receiver<String>>` to implement `Send` ``` The senders, by contrast, are shareable: `Sender<T>` has implemented `Sync` since Rust 1.72, and `SyncSender<T>` is `Sync` as well, so producers can even share one sender by reference, for example inside `thread::scope`. ## Option 1: `Arc<Mutex<Receiver<T>>>` The std-only fix for a pool of four encoder workers is to put the `Receiver` behind a `Mutex` and share that: 1. `let rx = Arc::new(Mutex::new(rx));` and clone the `Arc` into each worker. 2. In each worker: `let job = rx.lock().unwrap().recv();` as its own statement, then process `job`. It works, with costs worth naming in an interview: - Only one worker at a time can be inside `recv`; the others wait on the `Mutex`, not on the channel. For coarse jobs (an image encode taking milliseconds) that is irrelevant; for many tiny messages the lock becomes the bottleneck. - Where the guard is dropped matters. Binding the job in a separate `let` releases the lock at the end of that statement; writing `while let Ok(job) = rx.lock().unwrap().recv()` keeps the guard alive for the whole loop body, so the workers process one at a time. The material on `Mutex` covers that temporary-lifetime trap. - A worker that panics while holding the guard poisons the `Mutex` for the rest. ## Option 2: `crossbeam-channel` `crossbeam-channel` (0.5.17, the version checked here) describes itself as multi-producer, multi-consumer channels, "an alternative to `std::sync::mpsc` with more features". What it changes: | | `std::sync::mpsc` | `crossbeam_channel` | |---|---|---| | constructors | `channel()`, `sync_channel(n)` | `unbounded()`, `bounded(n)` (`bounded(0)` is zero-capacity) | | sender types | `Sender<T>` and `SyncSender<T>` | one `Sender<T>` for both | | `Receiver` is `Clone` / `Sync` | no / no | yes / yes | | wait on several channels | no stable way | `select!`, `select_biased!`, `Select` | | timers as channels | none | `after(d)`, `tick(d)`, `never()` | | queue inspection | none | `len()`, `is_empty()`, `is_full()`, `capacity()` | Cloning a crossbeam `Receiver` creates another handle on the **same** queue, not a copy of the stream: each message goes to exactly one of the receivers. That makes it a natural work queue: clone the `Receiver` into every encoder, and the channel distributes jobs. Disconnection works by drops on both sides, as in std, and iteration ends when the channel is empty and every `Sender` is gone. ## `select!` and its sharp edges `crossbeam_channel::select!` waits until one of several operations is ready and runs that arm, optionally with a `default` arm (immediately, or after a duration). Points a senior answer covers: - When several operations are ready at once, `select!` picks **one at random**; `select_biased!` always takes the first listed. Random choice keeps a busy channel from starving the others. - A receive on a **disconnected** channel counts as ready and yields `Err`. A loop that ignores that `Err` spins at full speed; break out, or swap the arm's receiver for `never()` once it closes. - `tick(d)` yields an `Instant` on a period, which gives a heartbeat or a flush timer without a separate thread. ## When to switch Since Rust 1.67, `std::sync::mpsc` has been implemented on a port of crossbeam-channel's code, so raw speed is no longer the main argument. Switch when you need what std lacks: **several consumers on one queue**, **waiting on more than one channel**, timer channels, or one sender type for both flavours. Stay on std when a single consumer fits, since it adds no dependency. Std's own multi-consumer `std::sync::mpmc` exists but is unstable, so stable code cannot use it.
- In crossbeam-channel, what happens to a `select!` loop when one of its channels disconnects?A receive on a disconnected channel counts as ready and returns `Err`, so that arm fires on every iteration. If the loop ignores the `Err` it spins, burning a core, and the closed arm keeps competing in every random choice. Break when the last input closes, or replace the closed receiver with `crossbeam_channel::never()` so its arm can no longer fire.
- Why might `Arc<Mutex<Receiver<T>>>` be good enough for the encoder pool?Encoding a frame takes far longer than taking one from the queue, so workers spend almost all their time outside the lock and contention is negligible. It keeps the code on std with no new dependency. It stops being good enough when messages are tiny and frequent, when you need `select!`, or when guards are held during processing.
- Suggests calling rx.clone() on a std Receiver to give each worker a copy.
- Thinks wrapping the Receiver in Arc makes it shareable across threads.
- Believes cloning a crossbeam Receiver duplicates every message to each clone.
- Claims crossbeam's select! always picks the first ready arm.
- Recommends crossbeam purely because std's channel is slow.
Assumes Rust 1.99; std::sync::mpsc has used a port of crossbeam-channel since 1.67, Sender has been Sync since 1.72, and std::sync::mpmc is still unstable.