skip to content

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%

answer

  1. what happens when the consumer is slow
  2. pre-allocated buffer
  3. SyncSender blocks when full
  4. bound zero means hand-off

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.

solid answer

~30 s

`channel()` returns a `Sender<T>` over a conceptually infinite buffer, so `send` never waits for space and a slow consumer lets the queue grow in memory. `sync_channel(n)` returns a `SyncSender<T>` over a pre-allocated buffer of `n` slots: `send` blocks while the buffer is full, which slows producers to the consumer's pace, and `try_send` returns `TrySendError::Full(v)` instead of blocking. The `Receiver` is the same type for both. A bound of zero is a rendezvous channel: there is no buffer, each `send` returns only when a `recv` has taken the value, so success means it was received.

code

rust · 29 lines
rust
use std::sync::mpsc::{self, TrySendError};
use std::thread;
use std::time::Duration;

fn main() {
    // at most 2 decoded frames may wait for the resize stage
    let (tx, rx) = mpsc::sync_channel::<Vec<u8>>(2);
    tx.send(vec![0; 4]).unwrap();
    tx.send(vec![1; 4]).unwrap();
    // buffer full: try_send refuses and hands the value back
    match tx.try_send(vec![2; 4]) {
        Err(TrySendError::Full(frame)) => println!("full, kept {} bytes", frame.len()),
        other => println!("unexpected {other:?}"),
    }
    let decoder = thread::spawn(move || {
        tx.send(vec![3; 4]).unwrap(); // blocks until the consumer frees a slot
        println!("decoder unblocked");
    });
    thread::sleep(Duration::from_millis(50));
    for frame in rx {
        println!("resize {:?}", frame[0]);
    }
    decoder.join().unwrap();

    // bound 0: a rendezvous, so try_send fails unless a receiver is already waiting
    let (rtx, rrx) = mpsc::sync_channel::<u8>(0);
    assert!(matches!(rtx.try_send(1), Err(TrySendError::Full(1))));
    drop(rrx);
}

go deeper

for a junior

Know that channel() never makes the sender wait, while sync_channel(n) blocks the sender once n messages are queued.

for a middle

Explain back-pressure, try_send and TrySendError::Full, and the rendezvous meaning of a zero bound.

for a senior

Show you size bounds from memory and latency, and spot the same-thread send that deadlocks on a full or zero-bound channel.

for a principal

Argue for bounded links as the default in long-running pipelines, so overload slows producers instead of exhausting memory.

## Two constructors, two sending types `std::sync::mpsc` offers two ways to make a channel, and they return different sender types: - **`mpsc::channel()`** returns `(Sender<T>, Receiver<T>)`. The docs call it asynchronous with a conceptually **infinite buffer**: `Sender::send` never waits for space. If producers outrun the consumer, the queue simply grows in memory. - **`mpsc::sync_channel(bound)`** returns `(SyncSender<T>, Receiver<T>)`. The storage for pending messages is a **pre-allocated buffer of `bound` slots**, and `SyncSender::send` **blocks** while that buffer is full, until the consumer takes a message. The `Receiver<T>` is the same type in both cases, with the same `recv`, `try_recv`, `recv_timeout` and iteration behaviour, and both keep first-in, first-out order. The difference is entirely on the sending side. Because `Sender<T>` and `SyncSender<T>` are distinct types, a function written to take a `Sender<T>` will not accept a `SyncSender<T>`; a stage that should work with either usually takes a closure such as `impl Fn(T)` or a small trait of your own. | | `channel()` | `sync_channel(n)`, n > 0 | `sync_channel(0)` | |---|---|---|---| | sender type | `Sender<T>` | `SyncSender<T>` | `SyncSender<T>` | | buffer | grows without limit | fixed, `n` slots | none | | `send` when full | never full | blocks for a free slot | blocks until a `recv` pairs with it | | non-blocking send | not needed | `try_send` -> `TrySendError::Full(v)` | `try_send` fails unless a receiver waits | | successful `send` means | queued | queued | received | ## Back-pressure: why the bound matters In the image pipeline, decoding is fast and encoding is slow. With `channel()` between them, the decoder keeps producing and every decoded frame waits in the queue; at a few megabytes per frame, a long input grows memory until the process is killed. With `sync_channel(4)`, at most four decoded frames wait. The fifth `send` blocks the decoder until the encoder catches up, so the slowest stage sets the pace. That automatic slowing of producers is called **back-pressure**, and it is the main reason to choose the bounded constructor. Choosing a bound is a trade: 1. **Memory ceiling**: roughly `bound * size_of_message` per link, plus whatever the messages own on the heap. 2. **Smoothing**: a buffer of a few messages absorbs jitter, so a stage that is briefly slow does not stall its neighbours on every message. 3. **Latency**: a deep buffer means a message can sit in the queue for a long time before anyone touches it. ## `try_send` when blocking is not acceptable `SyncSender::try_send(v)` never blocks. It returns `Err(TrySendError::Full(v))` when the buffer is full and `Err(TrySendError::Disconnected(v))` when the `Receiver` is gone; both variants hand the value back. That suits a producer that must not stall, such as an audio or input thread that would rather drop or coalesce a sample than wait. `Sender` from `channel()` has no `try_send`, because its `send` never waits for space in the first place. ## `sync_channel(0)`: the rendezvous channel A bound of **zero** is allowed and changes the meaning: there is no buffer at all. The docs call it a **rendezvous** channel, where each `send` "will not return until a `recv` is paired with it". Consequences: - A successful `send` guarantees the receiver has the value, which no buffered channel promises. - `try_send` returns `Full` unless a receiver is already blocked in `recv` at that moment. - Producer and consumer proceed in lock step, which is useful as a hand-off or a synchronisation point, and costly as a throughput link. A zero bound does not mean unbounded and does not mean the channel cannot carry messages; it means each message is handed over directly. ## Things that trip people up - Calling `send` on a full `sync_channel` from the **same thread** that is supposed to `recv` deadlocks that thread: it waits for space that only it could free. With `sync_channel(0)`, the very first `send` on the consumer's own thread does it. - A bounded channel still disconnects by drops, exactly like the unbounded one; a producer blocked in `send` wakes with `Err(SendError(v))` if the `Receiver` is dropped. - Clone a `SyncSender` for several producers just as you clone a `Sender`; the bound applies to the shared buffer, not per producer. - `crossbeam_channel::bounded(n)` and `unbounded()` mirror these two constructors with one `Sender` type for both, which is one reason teams that need both flavours in one API reach for it.

  • How would you pick the bound for the link between a fast decoder and a slow encoder?
    Start from memory: bound times the size of one decoded frame must fit the budget. Then size for jitter, a few messages so brief stalls do not ripple through every stage. Beyond that, a deeper buffer mostly adds latency, since the slowest stage sets the sustained rate. Measure how often producers block and adjust.
  • Why can a single-threaded test deadlock on `sync_channel(0)`?
    With no buffer, `send` returns only when a `recv` takes the value. If the same thread calls `send` before it ever calls `recv`, it waits for a receiver that can only be itself, and never returns. Run the sender on another thread, or use `try_send` to probe.

  • Thinks sync_channel(0) means an unbounded channel.
  • Believes channel() blocks the sender once some internal limit is reached.
  • Says sync_channel's send returns an error when the buffer is full.
  • Assumes a Sender and a SyncSender are the same type.
  • Assumes a successful send on a buffered channel proves delivery.