Sub topic 8
How channels close
This chapter assumes you can spawn threads, send values with mpsc::channel, and read Result values. A channel has no close() method. It closes when one end is dropped, and the other end finds out through an error.
Closing from the sending side
A channel stays open while at least one Sender exists. When the last Sender is dropped, the receiver can still read every message already in the buffer. After that, recv returns Err(RecvError).
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel::<i32>();
tx.send(1).unwrap();
drop(tx);
println!("{:?}", rx.recv());
println!("{:?}", rx.recv());
}This prints Ok(1) and then Err(RecvError). The message sent before the drop is not lost.
Iterating over a receiver with for value in rx is the same as calling recv in a loop and stopping at the first Err. This is why the loop in the earlier chapter ended by itself once the sending thread finished and its tx was dropped.
Closing from the receiving side
If the Receiver is dropped, nobody can read messages any more. send then returns Err(SendError), and the error hands your value back.
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel::<String>();
drop(rx);
match tx.send("hello".to_string()) {
Ok(()) => println!("sent"),
Err(e) => println!("receiver gone, got back: {}", e.0),
}
}A producer can treat this error as a signal to stop working. Calling unwrap on it would instead panic the producer thread, which is often not what you want.
Telling empty from closed
With try_recv and recv_timeout, an empty channel and a closed channel are different outcomes. recv_timeout reports them as Timeout and Disconnected.
use std::sync::mpsc::{self, RecvTimeoutError};
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel::<i32>();
match rx.recv_timeout(Duration::from_millis(50)) {
Ok(v) => println!("got {v}"),
Err(RecvTimeoutError::Timeout) => println!("timed out, sender still alive"),
Err(RecvTimeoutError::Disconnected) => println!("all senders dropped"),
}
drop(tx);
match rx.recv_timeout(Duration::from_millis(50)) {
Ok(v) => println!("got {v}"),
Err(RecvTimeoutError::Timeout) => println!("timed out, sender still alive"),
Err(RecvTimeoutError::Disconnected) => println!("all senders dropped"),
}
}Only Disconnected means no more messages will ever arrive. Timeout means you can wait again.
The common bug: a forgotten Sender
With several producers, every Sender must be dropped before the receiving loop can end. The easy one to forget is the original tx that you cloned from.
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(format!("worker {id} done")).unwrap();
});
}
drop(tx);
for msg in rx {
println!("{msg}");
}
}If you delete drop(tx), the program hangs after printing three lines. The main thread still owns a Sender, so the channel never reports closure, and the for loop waits forever.
Two other ways to leave a Sender alive are storing it in a long-lived struct and moving it into a thread that never exits.
Summary of the rules
| Event | Sender side sees | Receiver side sees |
|---|---|---|
| All `Sender`s dropped | Nothing | Buffered items, then `Err` or end of iteration |
| `Receiver` dropped | `send` returns `Err(SendError)` | Not applicable |
| Some `Sender`s remain | Normal sends | `recv` blocks when empty |
Exercise
A program clones tx into four worker threads and iterates over rx in main. All four workers finish, but the loop never ends. The code never calls drop(tx). Why does it hang, and what is the fix?
Show answer
The original tx in main is still alive, so the channel is not closed even though every clone is gone. The receiving loop keeps waiting for a possible message. Call drop(tx) after creating the clones, before the loop, or move the original into the last worker instead of cloning it.