Fix a for value in rx loop that never ends after every worker has finished
Three workers each send one number, and main adds up everything that arrives. Every worker finishes almost at once, yet the program never prints the total and hangs with no error. Find why the loop keeps waiting and fix it.
Requirements:
- Keep the three worker threads and the
for value in rxloop. - Do not hard-code how many messages to receive.
- The program prints
total: 60and exits.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
for id in 1..=3 {
let tx = tx.clone();
thread::spawn(move || {
tx.send(id * 10).unwrap();
});
}
let mut total = 0;
for value in rx {
total += value;
}
println!("total: {total}");
}Find and fix the bug.
The workers drop only their clones, while the original tx stays alive in main, so the channel never closes and for value in rx keeps waiting. Call drop(tx) right after spawning the workers; the program then prints total: 60.
- Assuming the channel closes when the workers finish, though the original
txinmainstill counts as a live sender - Adding
joincalls to fix the hang, which waits for the threads but leaves the channel open - Hard-coding three
recvcalls, which hides the bug and breaks as soon as the number of workers changes
- How would scoping
txinside a block remove the need for an explicitdrop? - What does
sendreturn in a worker ifmainhas already droppedrx?
A loop over a Receiver ends when the channel is closed, and the channel is closed when every Sender is dropped. Each worker drops its clone when its closure ends, but the original tx still lives in main, so for value in rx faithfully waits for a message this last sender could still send. There is no error: the program simply hangs.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
for id in 1..=3 {
let tx = tx.clone();
thread::spawn(move || {
tx.send(id * 10).unwrap();
});
}
drop(tx); // the original sender no longer keeps the channel open
let mut total = 0;
for value in rx {
total += value;
}
println!("total: {total}"); // total: 60
}A join before the loop does not cure the hang: the threads finish, but the tx in main remains. Instead of an explicit drop, you can limit tx to a block that spawns the workers; it is dropped at that block's closing brace.