Explanation
What just happened
main moved tx into a producer thread and waited in recv() while the channel was empty. Each send returned at once, so the producer never waited for main. When the producer ended, tx was dropped, and main’s loop ended.
Try the what-if switch
- two senders (tx.clone): each worker gets its own
tx. main drops the original, so the loop ends after the last worker. - forgot drop(tx): main keeps its
tx. All four messages arrive, then main waits forever.
Why the loop ends
for msg in rx calls recv() until it fails, and it fails only when the channel is empty and no Sender is left. Until then, another message could still come, so it waits.
When to use it
Pass results from worker threads to one collecting thread, with no lock. For one value many threads change, use Arc<Mutex<T>>.
Watch out
An extra Sender anywhere means the loop never ends, and nothing reports it.
Common questions
Why does my for loop over an mpsc Receiver never end?
A Sender is still alive somewhere, often the original tx in main after you cloned it for the workers. The loop ends only once every Sender is dropped, so add drop(tx) after handing out the clones.
Does mpsc send block until the value is received?
No. mpsc::channel() has no size limit, so send puts the value in the channel and returns. Only recv waits, and only while the channel is empty.
Can several threads receive from one mpsc channel?
No: mpsc means multiple producer, single consumer. tx.clone() works, but rx.clone() fails to compile with error E0599.
Verified: this timeline matches a real program, checked in CI on Rust 1.99 with Tokio 1.54. How we verify. Unclear or wrong? Tell us