Created
December 23, 2024 04:45
-
-
Save wpcarro/e467acdbf39c6f01e74777887be359ae to your computer and use it in GitHub Desktop.
Thread supervisor with restarts
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
#[derive(Debug, Clone, Copy)] | |
enum ThreadState { | |
Unstarted, | |
Panicked, | |
Success, | |
} | |
fn main () { | |
let x = Arc::new(Mutex::new(ThreadState::Unstarted)); | |
let run = |f: fn() -> ()| { | |
let x2 = Arc::clone(&x); | |
let x3 = Arc::clone(&x); | |
thread::spawn(move || { | |
panic::set_hook(Box::new(move |_| { | |
*x2.lock().unwrap() = ThreadState::Panicked; | |
})); | |
f(); | |
*x3.lock().unwrap() = ThreadState::Success; | |
}); | |
}; | |
let do_work = || { | |
sleep(Duration::from_secs(3)); | |
if *[true, false].choose(&mut thread_rng()).unwrap() { | |
panic!("Oops"); | |
} else { | |
println!("Success"); | |
} | |
}; | |
run(do_work); | |
loop { | |
let value = { | |
*x.lock().unwrap() | |
}; | |
match value { | |
ThreadState::Panicked => { | |
println!("Thread panicked. Restarting..."); | |
*x.lock().unwrap() = ThreadState::Unstarted; | |
run(do_work); | |
} | |
ThreadState::Success => { | |
println!("Supervision done. Exiting..."); | |
break; | |
} | |
_ => { | |
println!("Waiting..."); | |
} | |
} | |
sleep(Duration::from_secs(1)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment