expression

Graceful channel closure: drop every sender

For an end-of-stream protocol, producers own their sender clones and release them when finished. Retaining the original sender in a coordinator keeps the channel open. Drain queued work before joining producers that may be blocked on capacity. Expected stdout (not executed): 7 Common mistake: Leaving a coordinator sender alive while waiting for iterator completion.

Formal Syntax & Structure

rust syntaxrust
drop(original_sender); drop(clones); drain receiver

Working Example

Example Snippetrust
fn main() {    use std::{sync::mpsc, thread};    let (tx, rx) = mpsc::sync_channel(1);    let child_tx = tx.clone();    let h = thread::spawn(move || { child_tx.send(3).unwrap(); child_tx.send(4).unwrap(); });    drop(tx);    let sum: i32 = rx.into_iter().sum();    h.join().unwrap();    println!("{sum}");}
Rust Reference