Skip to content

Instantly share code, notes, and snippets.

@yammmt
Created June 3, 2020 11:35
Show Gist options
  • Save yammmt/e0e6bdf3767b61ced24f57c232a236b3 to your computer and use it in GitHub Desktop.
Save yammmt/e0e6bdf3767b61ced24f57c232a236b3 to your computer and use it in GitHub Desktop.
close interactive rayon thread safely
use std::time::{Duration, SystemTime};
use std::sync::mpsc;
use std::thread;
#[derive(Debug)]
enum ThreadMessage {
Hello,
Close,
}
fn another_thread(
tx: mpsc::Sender<ThreadMessage>,
rx: mpsc::Receiver<ThreadMessage>
) {
loop {
match rx.recv().unwrap() {
ThreadMessage::Hello => {
println!("Hello from main");
tx.send(ThreadMessage::Hello).unwrap();
},
ThreadMessage::Close => {
tx.send(ThreadMessage::Close).unwrap();
break;
}
}
}
}
fn main() {
let (tx1, rx1) = mpsc::channel();
let (tx2, rx2) = mpsc::channel();
rayon::spawn(move || {
another_thread(tx1, rx2);
});
let t = SystemTime::now();
loop {
if t.elapsed().unwrap() < Duration::from_secs(10) {
tx2.send(ThreadMessage::Hello).unwrap();
} else {
tx2.send(ThreadMessage::Close).unwrap();
}
match rx1.recv().unwrap() {
ThreadMessage::Hello => println!("Hello from thread"),
ThreadMessage::Close => return,
}
thread::sleep(Duration::from_secs(2));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment