Back to questions
JuniorTheoryCommon
What does the program print (lines separated by spaces)?
fn main() {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
for i in 1..=3 {
tx.send(i).unwrap();
}
});
for x in rx {
println!("{x}");
}
}1 2 3
- Expecting the loop to hang after
3: the channel closes when every sender is dropped, and the onlytxmoved into the thread, which drops it when it ends. - Expecting nothing because
mainhas nojoin:for x in rxblocks on each message, somainwaits for the thread through the channel itself.
- What would happen if
mainclonedtxbefore spawning and kept the clone alive? - How does the order change when three threads each send one number through clones of
tx?