What is the correct way of doing this? only the first send call works in the following code. can't get the second one to work
use std::thread;
use std::sync::mpsc::{channel, Sender};
use std::time::Duration;
fn test(sender: Sender<&'static str>) {
thread::spawn(move || {
sender.send("level 2");
});
}
fn main() {
let (sender, receiver) = channel();
let sender2 = sender.clone();
thread::spawn(move || {
sender2.send("level 1");
test(sender2);
});
thread::sleep(Duration::from_secs(2)); // block for two seconds
println!("{}", receiver.recv().unwrap()); // Received immediately
}
naim
June 4, 2020, 8:34pm
2
receiver.recv()
is only called once, and then receiver
is dropped. Once the receiver end is dropped (after the first call to recv
) the sender
s will fail. In this case it's a race condition since the threads aren't joined in the main thread.
If the sleep is placed after the first recv, then the second send
will probably be successful.
1 Like
tx, Join can be used as described but in my case threads never end. here is the fixed code in case anyone needed it
use std::thread;
use std::sync::mpsc::{channel, Sender};
use std::time::Duration;
fn test(sender: Sender<&'static str>) {
thread::spawn(move || {
sender.send("level 2");
});
}
fn main() {
let (sender, receiver) = channel();
let sender2 = sender.clone();
thread::spawn(move || {
sender2.send("level 1");
test(sender2);
});
loop {
thread::sleep(Duration::from_secs(2)); // block for two seconds
println!("{}", receiver.recv().unwrap()); // Received immediately
}
}
system
Closed
September 3, 2020, 7:56am
4
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.