mpsc channels: send, recv, and when the loop ends

Read the explanation
What if

send never waits for main: the value goes into the channel. main waits in recv(), and its for loop ends once the producer drops tx.

Predict first

The producer calls tx.send("a"). Does send wait until main takes the value out of the channel?

012345678910111213channel()spawnrecv()got arecv()got brecv()got cdoneworksend aworksend bworksend cdrop tx

Tap any block to see what that thread is doing.

  • Running
  • Waiting / parked
Step 1/7

A channel: tx sends, rx receives. Both lanes are OS threads.

1fn main() {2    let (tx, rx) = mpsc::channel();3    thread::spawn(move || {4        for job in ["a", "b", "c"] {5            thread::sleep(Duration::from_millis(50)); // some work6            tx.send(job).unwrap();7        }8    }); // the thread ends and drops tx9    for job in rx {10        println!("got {job}");11    }12    println!("done");13}

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

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