Sub topic 8
How Channels Close
This chapter assumes you can spawn and join threads, write move closures, and use Result and unwrap. It also assumes you have sent values through an mpsc channel. Here you learn when a channel counts as closed, what each side sees when that happens, and how that ends loops and prevents hangs.
Closing is implicit
An mpsc channel has no close() method. The channel closes when one end of it is dropped. A value is dropped when its owner goes out of scope, when you pass it to drop, or when a thread that owns it finishes or panics.
Each side watches the other:
- The
Receiversees the channel as closed when everySenderand every clone of it has been dropped. - A
Sendersees the channel as closed when theReceiverhas been dropped.
Neither side gets a signal when you drop its own end. The effect shows up on the other side as an Err from the next operation.
What the receiver sees: senders are gone
When all senders are dropped, the receiver does not lose the messages already queued. It reads them first. Only when the queue is empty does recv return Err(RecvError).
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel();
tx.send("a").unwrap();
tx.send("b").unwrap();
drop(tx);
println!("{:?}", rx.recv());
println!("{:?}", rx.recv());
println!("{:?}", rx.recv());
}The output is:
Ok("a")
Ok("b")
Err(RecvError)The Draining state in the diagram is this phase. The senders are gone, but the data is still readable.
A for loop over a receiver calls recv repeatedly and stops at the first Err. This is why for value in rx ends on its own once every sender is dropped. rx.iter() behaves the same way.
What the sender sees: the receiver is gone
When the Receiver is dropped, send fails. The error is SendError<T>, which wraps the value you tried to send. You get the value back instead of losing it.
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel::<String>();
drop(rx);
match tx.send(String::from("hello")) {
Ok(()) => println!("sent"),
Err(e) => println!("receiver gone, got back {:?}", e.0),
}
}send on an unbounded channel never blocks. Its only failure is a missing receiver. That makes send errors a useful shutdown signal: a producer can treat Err as "nobody wants more work" and stop.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::sync_channel::<u32>(1);
let producer = thread::spawn(move || {
let mut sent = 0;
for i in 0u32.. {
if tx.send(i).is_err() {
break;
}
sent += 1;
}
sent
});
let first: Vec<u32> = rx.iter().take(3).collect();
drop(rx);
let sent = producer.join().unwrap();
assert!(sent >= 3);
println!("{first:?}");
}This example uses sync_channel on purpose. A blocked send on a full bounded channel also returns Err when the receiver is dropped, so the producer wakes up and exits. With an unbounded channel the producer would race ahead and queue a huge number of values first.
When the receiver is dropped, any messages still queued are dropped with it. The sender has no way to learn which of its successful send calls were never read.
The most common bug: the forgotten sender
The receiving loop ends only when every sender is gone. The usual setup creates one tx and clones it for each worker. The original tx stays alive in main, so the loop never finishes. This program hangs:
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
for id in 0..3 {
let tx = tx.clone();
thread::spawn(move || {
tx.send(id).unwrap();
});
}
// BUG: the original `tx` is still alive here.
for value in rx {
println!("got {value}");
}
}All three workers finish and drop their clones. The original tx is still owned by main, so the channel is not closed. The for loop blocks forever waiting for a message that no thread can send.
The fix is one line, drop(tx);, placed after the loop that spawns the workers and before the receiving loop. This is the same pattern as the multiple-producer example earlier in this tutorial. If you can move the original tx into a spawned thread instead, that works too.
The same bug also appears in worker pools. If the thread that hands out jobs keeps its job_tx alive, the workers wait on recv forever. Dropping job_tx is how you tell every worker to stop.
Telling empty from closed
The other receiving methods report closure too. They differ in how they tell "nothing yet" apart from "nothing ever again".
| Call | Queue has a message | Queue empty, a Sender is alive | Queue empty, all Senders dropped |
|---|---|---|---|
| `recv()` | `Ok(value)` | Blocks until a message or closure | `Err(RecvError)` |
| `try_recv()` | `Ok(value)` | `Err(TryRecvError::Empty)` | `Err(TryRecvError::Disconnected)` |
| `recv_timeout(d)` | `Ok(value)` | `Err(RecvTimeoutError::Timeout)` after `d` | `Err(RecvTimeoutError::Disconnected)` |
| `for v in rx` | next `v` | Blocks | Loop ends |
try_recv is useful when a thread has other work to do and only checks the channel now and then. You must handle Disconnected explicitly, or the loop will poll forever:
use std::sync::mpsc::{self, TryRecvError};
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
let worker = thread::spawn(move || {
for i in 0..3 {
tx.send(i).unwrap();
thread::sleep(Duration::from_millis(20));
}
});
loop {
match rx.try_recv() {
Ok(v) => println!("got {v}"),
Err(TryRecvError::Empty) => thread::sleep(Duration::from_millis(5)),
Err(TryRecvError::Disconnected) => {
println!("done");
break;
}
}
}
worker.join().unwrap();
}Empty means "try again later". Disconnected means "stop trying". A loop that treats both the same way either spins forever or quits too early.
Panics also close channels
When a thread panics, Rust unwinds its stack and drops everything it owns. If that includes a Sender, the channel can close just as if the thread had returned normally.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
let handle = thread::spawn(move || {
tx.send(1).unwrap();
panic!("worker failed");
});
for v in rx {
println!("got {v}");
}
match handle.join() {
Ok(()) => println!("worker finished"),
Err(_) => println!("worker panicked"),
}
}The receiving loop prints got 1 and then ends, because the panicking thread dropped its Sender. The loop ending does not tell you whether the worker succeeded. To find out, call join and check the Result. A closed channel means "no more messages", not "everything went well".
If your protocol needs to distinguish a clean finish from a failure, send an explicit final message such as a Done variant of an enum. You can also rely on join.
Design rules that follow
- Treat the end of a
recvloop as the normal "no more work" signal, and arrange for senders to be dropped to trigger it. - Treat
senderrors as "the consumer is gone". Decide whether to stop, log, or recover the value fromSendError. - Do not call
unwraponsendwhere the receiver may legitimately exit first.unwrapthere turns an orderly shutdown into a panic in the producer. - Keep ownership of
Sendervalues clear. Move them into the threads that need them, and drop spares as soon as you finish cloning.
Exercise
A program clones tx into four worker threads, then runs for msg in rx { ... } on the main thread. All four workers finish, but the loop never ends. What is wrong, and what is the smallest fix?
Show answer
The original tx is still owned by the main thread, so not every Sender has been dropped and the channel is not closed. Call drop(tx) after the workers are spawned and before the for loop starts. The loop then ends once the four clones are dropped as the workers finish.
Exercise
A consumer reads three messages from a channel, then drops its Receiver. The producer calls tx.send(value).unwrap() in a loop. What happens, and how would you change the producer so it exits cleanly?
Show answer
The next send returns Err(SendError(value)), so unwrap panics in the producer thread. Replace unwrap with a check such as if tx.send(value).is_err() { break; }. The producer then stops quietly when the receiver is gone.
Exercise
Why does try_recv return Err(TryRecvError::Empty) in one case and Err(TryRecvError::Disconnected) in another, and what does a polling loop do differently for each?
Show answer
Empty means no message is queued but at least one Sender is still alive, so more messages may arrive and the loop should wait and try again. Disconnected means the queue is empty and all Senders are dropped, so no message can ever arrive and the loop should exit.