Send Fails After Receiver Drop

sender.send reports SendError once the receiver has dropped, so shutdown detection needs no extra done channel on the worker side.

RustResilience

Code

rustsnippet
28 lines
use std::sync::mpsc;
use std::thread;

fn main() {
    let (sender, receiver) = mpsc::channel::<String>();

    let handle = thread::spawn(move || {
        // the worker consumes only the first two messages, then exits
        for msg in receiver.iter().take(2) {
            println!("handled: {msg}");
        }
        // receiver dropped here: the channel is closed
    });

    // the first two sends succeed while the receiver is alive
    sender.send("job-1".into()).unwrap();
    sender.send("job-2".into()).unwrap();

    handle.join().unwrap();

    // after the receiver is dropped, the send fails with SendError
    // and keeps the payload so it can be logged or re-routed
    let outcome = sender.send("job-3".into());
    match outcome {
        Ok(()) => println!("delivered"),
        Err(err) => println!("send failed, payload preserved: {}", err.0),
    }
}

What the code does

Send Fails After Receiver Drop comes down to the function main.

Repetition is confined to for msg in receiver.iter().take(2) — the rest of the file is straight-line. A match spells out every case; omit one and the code does not compile.

Using it

Output lines are prefixed (handled:, delivered, send failed, payload preserved:), making each step’s effect easy to spot.

Key statements

for msg in receiver.iter().take(2) {
    println!("handled: {msg}");
}
sender.send("job-1".into()).unwrap();
sender.send("job-2".into()).unwrap();

Interactive Tools for This Topic

FAQ

What does Send Fails After Receiver Drop print when run?
Running the file directly is enough — expect labeled output lines such as `handled:`, `delivered`, `send failed, payload preserved:`.