skip to content

Message-Passing Channels

std::sync::mpsc sends owned values between threads, and the receiver ends when every sender drops. Interviewers ask about bounded vs unbounded channels and when to prefer crossbeam.

on this pageshow

questions

5

In Rust's std::sync::mpsc, what happens to a value when a thread sends it, and how does another thread receive it?

level: juniorimportance: must knowfreq 80%

answer

  1. ownership, not copying
  2. send takes T by value
  3. use after send fails to compile
  4. recv blocks; for loop ends on disconnect

basics

~20 s

Sender::send takes the value by value, so ownership moves into the channel and any later use is error E0382. The receiving thread calls recv, which blocks until a message arrives, or loops with for msg in rx.

solid answer

~30 s

`mpsc::channel()` returns a `Sender<T>` and a `Receiver<T>`. `tx.send(value)` takes `T` by value, so the value moves into the channel: the sender can no longer use it, and touching it afterwards is E0382, "borrow of moved value". Nothing is cloned; a `String` crosses threads by handing over its buffer. On the other side `rx.recv()` blocks while the queue is empty and a `Sender` is alive, then returns `Ok(value)` and the receiver owns it. `for msg in rx` repeats `recv()` and ends once every `Sender` has been dropped and the queue is drained. Messages from one sender arrive in the order sent.

code

rust · 19 lines
rust
use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel::<String>();
    let decoder = thread::spawn(move || {
        for i in 1..=3 {
            let frame = format!("frame-{i:03}.png");
            tx.send(frame).unwrap(); // ownership of the String moves into the channel
        }
        // tx is dropped here, when the closure returns
    });
    for frame in rx {
        // blocks on each recv; ends once every Sender is gone
        println!("resize {frame}");
    }
    decoder.join().unwrap();
    println!("pipeline done");
}

go deeper

for a junior

Recall the pair from mpsc::channel, that send moves the value so a later use is E0382, and that recv blocks until something arrives.

for a middle

Explain why move semantics make message passing safe without a lock, and that a for loop over the Receiver ends only when every Sender is gone.

for a senior

Show you handle the Result from send instead of unwrapping by reflex, and that you pick explicit clones or Arc when both sides need the data.

for a principal

Frame ownership transfer as the design property: data owned by one stage at a time, so a reviewer checks hand-offs rather than lock discipline.

## What a channel is in Rust's standard library `std::sync::mpsc` (multi-producer, single-consumer) is the standard library's way to move values from one thread to another. Calling `mpsc::channel()` returns a pair: a **`Sender<T>`** (by convention `tx`) and a **`Receiver<T>`** (`rx`). Both are ordinary owned values: you move the `Sender` into a worker thread's `move` closure, keep the `Receiver` where the results are consumed, and the two halves stay connected through a shared queue. The element type `T` is fixed for the channel, and it is inferred from the first `send` when you do not write it out (`mpsc::channel::<String>()` spells it explicitly). To move a `Sender<T>` into a spawned thread, `T` must be `Send`; why some types are not is covered in the lesson on `Send` and `Sync`. ## `send` moves the value into the channel `Sender::send` has the signature `fn send(&self, t: T) -> Result<(), SendError<T>>`. The parameter is `T` **by value**, so a call is a **move**: - After `tx.send(frame)`, the sending thread no longer owns `frame`. Using it again is a compile error, **E0382** ("borrow of moved value"), exactly as with any other function that takes ownership. - Nothing is copied or cloned behind your back. A `String` or a `Vec<u8>` crosses threads by handing over its heap buffer, which is why channels are cheap for large values. - If the sender needs to keep a copy, it calls `.clone()` explicitly before sending, or sends something cheap to share such as an `Arc`. This is the property that makes message passing safe without locks: at any moment exactly one thread owns each value, and the compiler enforces it. The sender cannot mutate a frame after handing it over, because it no longer has a name for it. ```rust let frame = String::from("frame-001.png"); tx.send(frame).unwrap(); println!("sent {frame}"); // error[E0382]: borrow of moved value: `frame` ``` The usual fixes are to log before sending, or to send and log a cheap derived value (a length, an id) computed before the move. ## How the receiving thread gets values The `Receiver` offers several ways to take messages; the everyday one is blocking: 1. **`rx.recv()`** blocks the current thread while the queue is empty and at least one `Sender` (clones included) is still alive. When a message arrives it returns `Ok(value)`, and the receiving thread now owns it. 2. When every `Sender` has been dropped, `recv()` still hands out whatever was already queued, and only after the queue is empty returns **`Err(RecvError)`**: no more messages can ever arrive. 3. **`for msg in rx`** (or `for msg in &rx`, or `rx.iter()`) wraps that loop. `Receiver<T>` implements `IntoIterator`, and each step calls `recv()` and stops at the first `Err`. So the loop ends exactly when the channel is drained and disconnected; it never panics. Messages from one `Sender` arrive in the order they were sent (the docs promise first-in, first-out order); messages from several senders interleave in whatever order the sends happened. ## The three-stage image pipeline, first link | Step | Call | Ownership | |---|---|---| | decoder creates a frame | `let frame = ...` | decoder thread owns it | | decoder sends | `tx.send(frame)` | the channel owns it | | resizer receives | `rx.recv()` or `for frame in rx` | resizer thread owns it | | decoder finishes | closure returns, `tx` drops | resizer sees the end after draining the queue | In the runnable example, the decoder thread sends three `String`s and returns, which drops its `Sender`. The main thread's `for frame in rx` prints all three and then ends, because the only `Sender` is gone. Without that drop the loop would wait for ever, which is the most common channel bug and the subject of the question on disconnection. ## Points to say out loud in an interview - `send` takes ownership; a use after `send` is E0382, not a runtime surprise. - `recv` blocks; `try_recv` and `recv_timeout` are the non-blocking and bounded-wait variants. - A `for` loop over a `Receiver` ends when every `Sender` is dropped and the queue is empty. - The standard channel is single-consumer: the `Receiver` is not `Clone`, so one thread (or one owner) receives. - `send` returns a `Result` because the `Receiver` may already be gone; `unwrap()` there turns a dead consumer into a panic in the producer.

  • The decoder wants to log each frame after sending it. How do you keep that working?
    Log before the `send`, or compute what you need first (`let name_len = frame.len();`) and use that after the move. If the full value is really needed on both sides, clone it explicitly before sending or send an `Arc<T>` so both threads share one allocation; `send` itself never copies.
  • Why does `send` return a `Result` at all on an unbounded channel?
    Because the `Receiver` may already have been dropped. `send` then returns `Err(SendError(value))`, handing the value back, since it could never be received. An `Ok` only means the receiving half still existed at that moment; it does not prove the message will be read.
  • What is the difference between `for msg in rx` and `for msg in &rx`?
    Both block on each message and stop when the channel is drained and disconnected. `for msg in rx` consumes the `Receiver` (its `IntoIterator` impl takes it by value), so `rx` is unusable afterwards; `for msg in &rx` borrows it through `Receiver::iter`, so you can still call `try_recv` or iterate again later.

  • Says send copies or clones the value into the channel.
  • Thinks the sender can still read a value after sending it.
  • Believes recv returns immediately with an error when the queue is empty.
  • Expects a for loop over a Receiver to stop when the queue is momentarily empty.
  • Assumes several threads can each hold and read the same std Receiver.
open as a page

With Rust's std::sync::mpsc, why can a receive loop hang after every worker finishes, and what do send, recv, try_recv and recv_timeout report on disconnection?

level: middleimportance: must knowfreq 65%

basics

~20 s

A std Receiver only sees disconnection when every Sender, including the original kept in main, is dropped; until then recv blocks. recv then returns RecvError, try_recv and recv_timeout distinguish empty from disconnected, and send returns SendError with the value.

open as a page

In Rust's std::sync::mpsc, how does sync_channel(n) differ from channel(), and what does sync_channel(0) do?

level: middleimportance: should knowfreq 50%

basics

~20 s

channel() is unbounded: Sender::send never waits and the queue can grow without limit. sync_channel(n) has a fixed buffer, so SyncSender::send blocks when it is full, giving back-pressure. sync_channel(0) is a rendezvous: each send waits for a matching recv.

open as a page

In Rust, why can't four worker threads share one std::sync::mpsc::Receiver, and when would you switch to crossbeam-channel instead?

level: seniorimportance: should knowfreq 40%

basics

~20 s

std'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.

open as a page

Designing a Rust image pipeline with decode, resize and encode threads, when do you connect stages by channels rather than share state through Arc<Mutex<T>>?

level: principalimportance: should knowfreq 35%

basics

~20 s

Use channels when data flows one way through stages: each image is moved, bounded sync_channel links cap memory, and dropping senders shuts stages down in turn. Use shared state for read-mostly lookups, aggregates and random access that every thread needs.

open as a page