reison
March 28, 2020, 8:48am
1
I have code a test, every thread create a channel, and asynchronous receiver message,look this:
fn test(res:Receiver){
let res = res.recv();
if res.is_err(){
println!("{:?}",res.err().unwrap().to_string());
}
}
fn main() {
loop{
std::thread::sleep(Duration::from_secs(1));
std::thread::spawn(move ||{
let (mut sender,mut res) = std::sync::mpsc::sync_channel(1);
std::thread::spawn(move||{
test(res);
})
});
}
}
the error message is:"receiving on a closed channel"
why every channel was closed when it created?I do not understand,someone konw?pls help, thanks!
s3bk
March 28, 2020, 8:51am
2
Because you are dropping the sender immediately.
If there is no sender remaining, the channel is closed.
reison
March 28, 2020, 9:08am
3
oh, u are right!thanks,so how could I make sender is alive?I think loop send like the heartbeat is bad idea?
s3bk
March 28, 2020, 9:16am
4
If you want to send a heartbeat, then the channel needs to be created outside of the loop.
Basically:
create channel
spawn thread that sends a message to the sender every second.
receive messages from the channel in the main thread
reison
March 28, 2020, 9:17am
5
I make one clone of sender with receiver to make sender alive as long as receiver, when receiver was drop, the sender was drop too, but it is a bad way?!
system
Closed
June 26, 2020, 9:18am
6
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.