Created
June 3, 2020 11:35
-
-
Save yammmt/e0e6bdf3767b61ced24f57c232a236b3 to your computer and use it in GitHub Desktop.
close interactive rayon thread safely
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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