#[derive(Debug, Default)]
pub struct Quit {
pub bool: bool,
}
impl Quit {
pub fn handle_events(self) -> Arc<Mutex<Quit>> {
let quit: Arc<Mutex<Quit>> = Arc::new(Mutex::new(self));
{
let quit = Arc::clone(&quit);
thread::spawn(move || {
loop {
match event::read() {
Ok(Event::Key(key_event)) if key_event.kind == KeyEventKind::Press => {
match key_event.code {
KeyCode::Char('q') => {
Quit::quit(&quit);
}
_ => {}
}
}
Err(_) => {} //HANDLING NEEDED TODO
_ => {}
};
}
});
}
return quit;
}
}
fn main() -> anyhow::Result<()> {
let quit = Quit::default().handle_events(); //ERROR HANDLING TODO
// do stuff with quit WHILE THE THREAD IS RUNNING and IF handle_events()
//inner thread returns an error, UNWRAP IT AND FINISH THE PROGRAM
}
First of all, is it possible?
I know we have to use .join() to deal with the return type of the thread, but this makes the main thread wait for the other thread to end and THEN do something to the returned value. I want the caller thread to keep doing other stuff until it is returned.
I've thought of two solutions:
- turning Quit into an enum, so if it matches Err(_), use the other enum type that means that an error happened
- using a channel (Bad because only one Err(_) should be enough to stop the program, cost is too high)
But I feel like there are better options and I'm taking any good advice even if it means modifying the function format. Thank you!