Channels

Channels in Rust: The shop floor has six counters and one cashier's office. Every counter has a brass tube station of its own; the office has a single…

The Analogy: The Pneumatic Tube To The Cashier's Office

The shop floor has six counters and one cashier's office. Every counter has a brass tube station of its own; the office has a single receiving basket. A counter drops a canister in whenever it likes and carries straight on serving -- it does not wait for a reply and it has no idea what the office is doing. The office works through whatever lands in the basket.

What goes into the canister leaves you. Once it has dropped into the tube the docket is not on your counter any more: you cannot amend it, re-read it, or send it a second time. That is not a rule the tube imposes for its own amusement. It is what "it has gone to the office" means, and it is precisely why nobody has to agree with anybody about who is allowed to touch the docket.

Then there is order. Canisters from one counter reach the basket in the order that counter sent them, because they all went down the same pipe. Canisters from six counters reach the basket in whatever order six pipes happen to deliver them. The office is free to sort what it has collected; it cannot ask the pipes to cooperate, and a cashier who writes the day's ledger in arrival order will produce a different ledger every day from identical work.

Last, the end of the day, which is the part that catches everyone. The cashier does not work to a clock. The office closes when every tube station on the floor has been shut up and capped. Cap five of the six and leave the last one open with nobody standing at it, and the cashier waits all night for a canister that is never coming. The other direction is kinder: if the office closes first, the next canister comes straight back up the pipe with the docket still inside, so at least you know it was never dealt with.


Syntax or Core Structure

A channel is a one-way queue between threads: many senders, exactly one receiver.

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    for bay in 1..=3 {
        let tx = tx.clone();

        thread::spawn(move || {
            for n in 1..=2 {
                tx.send((bay, bay * 100 + n)).unwrap();
            }
        });
    }

    drop(tx);

    let mut received: Vec<(i32, i32)> = rx.iter().collect();

    println!("count {}", received.len());

    received.sort();

    for (bay, docket) in &received {
        println!("bay {bay}  docket {docket}");
    }
}

Output:

count 6
bay 1  docket 101
bay 1  docket 102
bay 2  docket 201
bay 2  docket 202
bay 3  docket 301
bay 3  docket 302

mpsc stands for multi-producer, single-consumer, and the shape of the API follows from that: Sender can be cloned as often as you like, Receiver cannot be cloned at all. Each thread got its own tx and sent two tuples; the receiver collected all six and sorted them, because six pipes deliver in no particular order.

The drop(tx) on its own line is not tidying up. It is the reason this program finishes, and the next section is about nothing else.

What it does
mpsc::channel()Returns a Sender<T> and a Receiver<T>, with unbounded capacity
tx.send(v)Moves v into the channel. Returns Err only if the receiver is gone
rx.recv()Blocks until a value arrives. Returns Err only when every sender is gone
tx.clone()Another sender for the same channel -- the "multi" in mpsc
for v in rxReceives until the channel closes, then the loop ends normally
drop(tx)Retires one sender. The channel closes when the last one is dropped

Technical Depth: How A Receiver Knows To Stop

It is not a count, and it is not a sentinel

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        tx.send("a-01").unwrap();
        tx.send("a-02").unwrap();
    });

    println!("first  {:?}", rx.recv());
    println!("second {:?}", rx.recv());
    println!("third  {}", rx.recv().is_err());
}

Output:

first  Ok("a-01")
second Ok("a-02")
third  true

The third recv fails because the spawned closure owned the only Sender and dropped it on the way out. That is the whole mechanism: a receiver learns that nothing more is coming from the disappearance of the last sender, not from a message count and not from a magic "finished" value.

Which is also the single most common hang in Rust. In the opening example the loop cloned tx three times, but the original was still sitting in main's scope, and a Sender in scope is a station left open. Without drop(tx) the iteration over rx waits for ever -- after all six values have already been sent and received. The alternatives are to drop it explicitly, or to arrange for the original to be moved into the last thread rather than cloned.

Asking instead of waiting

use std::sync::mpsc;
use std::sync::mpsc::TryRecvError;

fn main() {
    let (tx, rx) = mpsc::channel();

    println!("before {}", rx.try_recv() == Err(TryRecvError::Empty));

    tx.send(118).unwrap();

    println!("one    {:?}", rx.try_recv());
    println!("after  {}", rx.try_recv() == Err(TryRecvError::Empty));

    drop(tx);

    println!("closed {}", rx.try_recv() == Err(TryRecvError::Disconnected));
}

Output:

before true
one    Ok(118)
after  true
closed true

try_recv never blocks, and its two failure cases mean opposite things. Empty means "nothing right now, ask again"; Disconnected means "nothing ever again, stop asking". Only the second is terminal, and a loop that treats them as the same error either spins for ever or quits while work is still in flight. recv_timeout sits between the two: it waits, but not indefinitely.

Sending is moving, and a refused send hands the value back

use std::sync::mpsc;

fn main() {
    let (tx, rx) = mpsc::channel();
    let docket = String::from("a-01");

    tx.send(docket).unwrap();

    let back = rx.recv().unwrap();

    println!("received {back}  len {}", back.len());

    drop(rx);

    match tx.send(String::from("b-02")) {
        Ok(()) => println!("sent"),
        Err(e) => println!("refused, still holding {}", e.0),
    }
}

Output:

received a-01  len 4
refused, still holding b-02

After tx.send(docket) the name docket is unusable, because send takes its argument by value. That is what makes it safe to hand a String or a Vec to another thread with no lock anywhere in sight: exactly one thread can reach the value at any moment, and the channel is the moment it changes hands.

SendError is a tuple struct holding the value that could not be delivered, so e.0 gets it back. There is no other sensible design -- the channel refused to take ownership, so somebody has to still have it.

Bounded channels, and the queue that is really a leak

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::sync_channel(2);

    let sender = thread::spawn(move || {
        for n in 1..=5 {
            tx.send(n).unwrap();
        }

        "all queued"
    });

    let mut total = 0;

    for n in rx {
        total += n;
    }

    println!("total {total}");
    println!("{}", sender.join().unwrap());
}

Output:

total 15
all queued

With a capacity of two, the fourth send cannot proceed until the receiver has taken something out. That is backpressure, and it is the difference between a queue and a slow leak: an unbounded channel whose producer outruns its consumer grows until the process runs out of memory, with no error, no warning and a program that looks like it is working. sync_channel(0) takes it to the limit -- every send waits for a matching recv, so the two threads meet at each value and neither runs ahead.

channel()sync_channel(n)
CapacityUnboundedExactly n buffered values
send blocksNeverWhenever the buffer is full
Producer faster than consumerMemory grows without limitProducer is held to the consumer's pace
Right forBursty work with a known, finite totalStreams, pipelines, anything long-lived

Real World Example: Three Batches Reporting Down One Pipe

Three workers, three kinds of news, one channel, and a report that is identical on every run.

use std::sync::mpsc;
use std::thread;

enum Note {
    Parsed { worker: usize, bay: String, units: u32 },
    Rejected { worker: usize, row: String, why: &'static str },
    Finished { worker: usize, seen: usize },
}

fn parse(row: &str) -> Result<(String, u32), &'static str> {
    let (bay, value) = row.split_once('=').ok_or("no equals sign")?;

    if bay.is_empty() {
        return Err("empty bay");
    }

    let units = value.parse::<u32>().map_err(|_| "not a number")?;

    Ok((bay.to_string(), units))
}

fn main() {
    let batches = vec![
        vec!["a-01=118", "a-02=124", "a-03=x"],
        vec!["b-01=7", "=5", "b-02=131"],
        vec!["c-01=40", "c-02="],
    ];

    let (tx, rx) = mpsc::channel();

    for (worker, batch) in batches.into_iter().enumerate() {
        let tx = tx.clone();

        thread::spawn(move || {
            for row in &batch {
                match parse(row) {
                    Ok((bay, units)) => {
                        tx.send(Note::Parsed { worker, bay, units }).unwrap();
                    }
                    Err(why) => {
                        let row = row.to_string();

                        tx.send(Note::Rejected { worker, row, why }).unwrap();
                    }
                }
            }

            tx.send(Note::Finished { worker, seen: batch.len() }).unwrap();
        });
    }

    drop(tx);

    let mut parsed: Vec<(usize, String, u32)> = Vec::new();
    let mut rejected: Vec<(usize, String, &str)> = Vec::new();
    let mut finished: Vec<(usize, usize)> = Vec::new();

    for note in rx {
        match note {
            Note::Parsed { worker, bay, units } => parsed.push((worker, bay, units)),
            Note::Rejected { worker, row, why } => rejected.push((worker, row, why)),
            Note::Finished { worker, seen } => finished.push((worker, seen)),
        }
    }

    parsed.sort();
    rejected.sort();
    finished.sort();

    for (worker, bay, units) in &parsed {
        println!("ok   w{worker}  {bay:8} {units:4}");
    }

    for (worker, row, why) in &rejected {
        println!("bad  w{worker}  {row:8} {why}");
    }

    for (worker, seen) in &finished {
        println!("done w{worker}  seen {seen}");
    }

    let total: u32 = parsed.iter().map(|(_, _, units)| units).sum();

    println!("parsed {}  rejected {}  units {total}", parsed.len(), rejected.len());
}

Output:

ok   w0  a-01      118
ok   w0  a-02      124
ok   w1  b-01        7
ok   w1  b-02      131
ok   w2  c-01       40
bad  w0  a-03=x   not a number
bad  w1  =5       empty bay
bad  w2  c-02=    not a number
done w0  seen 3
done w1  seen 3
done w2  seen 2
parsed 5  rejected 3  units 420

The enum is the part to copy. A channel carries exactly one type, so anything with more than one kind of news needs an enum, and the receiver's match then becomes the single place in the program where every possible outcome is handled. Three variants cover it here: a row that parsed, a row that did not along with the reason, and a per-worker note saying the batch is done. Nothing is discarded and no second channel is needed to carry the failures.

drop(tx) again, and this time it is the only reason the program terminates. Three clones went into three threads, the original stayed in main, and for note in rx ends only when every sender has gone. Delete that one line and this program does all its work correctly, sends every note, and then hangs for ever without printing a character -- which is the worst class of bug to be handed, because nothing is broken and the process looks busy.

Sorting at the receiver is what makes the output reproducible. Notes arrive in whatever order three threads and one queue produce, and the three vectors are sorted before anything is printed, so the parsing genuinely happened in parallel while the report reads the same every time. Finished earns its place as a variant: it is how the receiver can tell that a worker completed its batch rather than merely stopping, and 3 + 3 + 2 coming to the eight rows that went in is a check the receiver can make without trusting anybody.

The limits are worth being blunt about. Everything is buffered before anything is printed, so this is a batch report dressed as a pipeline -- a genuinely streaming version would print each note on arrival and give up the sorted order, and you cannot have both. .unwrap() on every send is wrong in anything long-lived: a send fails when the receiver has gone, which is ordinary shutdown, and three threads panicking in parallel is a poor way to notice ordinary shutdown. The channel is unbounded, so a worker that outran main would grow the queue until memory ran out; sync_channel fixes that and costs you the guarantee that workers never block. And a panic inside a worker is invisible here, because the handles are dropped instead of joined -- the missing Finished note is the only evidence, and nothing in this code looks for it.


Common Mistakes

  1. Keeping the original tx alive after cloning it into the workers. The receiver waits for a sender that will never send. All the work completes, nothing is printed, and the process sits there. Drop it, on its own line, right after the spawn loop.
  1. Treating TryRecvError::Empty and Disconnected as one error. One means "not yet", the other means "never". Collapsing them gives you either an infinite spin or a receiver that stops while values are still in flight.
  1. send(...).unwrap() in a long-lived program. A failed send usually means the receiver shut down, which is normal. Panicking is a strange response to a normal event, especially from several threads at once.
  1. Expecting order across senders. Two senders have no relationship to each other. Values from one arrive in order; values from many arrive in whatever order they arrive.
  1. An unbounded channel with a producer faster than its consumer. There is no error and no back pressure -- just steadily growing memory in a program that appears to be working.
  1. Sending a sentinel "finished" value to end the loop. The sender being dropped already means that, and it cannot be forgotten, duplicated or sent early. Send a Finished note when you want the information, not to control the loop.
  1. Using a channel where a return value would do. Fixed fan-out with one result per worker is what join is for. Channels earn their keep when the number of messages is unknown or they need to arrive as they happen.
  1. Trying to clone the Receiver. It is multi-producer, single-consumer. If several threads need to take work from one queue, that is a shared queue behind a lock, or a crate designed for it.
  1. Forgetting that send moves. The value is gone from the sending thread. Clone before sending if you still need it, and notice that you are now paying for the clone.

Best Practices

  • Drop the original Sender immediately after the spawn loop, on its own line, with a comment saying why. It reads like dead code to anybody who has not been bitten.
  • Define one enum per channel and match it exhaustively at the receiver. Adding a message type then becomes a compile error everywhere it matters.
  • Handle Empty and Disconnected separately, always.
  • Prefer sync_channel for anything that runs indefinitely. Pick the capacity deliberately, and treat "unbounded" as a claim you are prepared to defend.
  • On SendError, take the value back out of it. You still own it, and dropping it silently loses work.
  • Sort or otherwise order at the receiver if you want a stable report. Arrival order is not a property of your program.
  • Join the worker handles as well as reading the channel, so a panicking worker is something the report can mention rather than something you infer from a missing message.
  • Keep the messages small and owned. A channel that carries large values pays for every one of them; sending an index or a summary is often enough.

Practice Exercises

  1. Delete the drop(tx) from the three-batch example and confirm that it hangs after doing all its work. Then fix it a second way: move the original tx into the final thread instead of cloning for it, and explain why that also works.
  1. Add a Note::Progress { worker, done } variant and print a running count as notes arrive rather than after the loop. Say exactly what you gave up by printing on arrival.
  1. Change the channel to sync_channel(1) and describe what now happens to the three workers while main is busy printing. Then set the capacity to 0 and describe the difference.
  1. Make one worker panic partway through its batch. Join the handles, detect which worker failed, and have the final line report it -- without unwrap-ing anything.