Expand description
§killswitch_std
killswitch_std is a simple crate with no dependencies outside of the standard library for creating a thread-safe kill switch
§Example
#[tokio::main]
async fn main() {
use killswitch_std::KillSwitch;
use std::time::Duration;
// Create a kill switch
let kill = KillSwitch::default();
println!("Is kill switch set? {}", kill);
// Now make a couple of clones and check
let k1 = kill.watcher();
let t1 = tokio::spawn(async move {
let duration = Duration::from_secs(2);
for _ in 0..5 {
tokio::time::sleep(duration).await;
println!("Kill switch on thread 1: {}", k1);
}
println!("Thread 1 wrapping up");
});
// Now make a couple of clones and check
let k2 = kill.watcher();
let t2 = tokio::spawn(async move {
let duration = Duration::from_secs(2);
for _ in 0..5 {
tokio::time::sleep(duration).await;
println!("Kill switch on thread 2: {}", k2);
}
println!("Thread 2 wrapping up");
});
let duration = Duration::from_secs(7);
tokio::time::sleep(duration).await;
println!("Flipping kill switch on main thread");
let _ = kill.kill();
let _ = tokio::join!(t1, t2);
println!("All threads finished");
}
Should produce output of the following form:
Is kill switch set? alive
Kill switch on thread 2: alive
Kill switch on thread 1: alive
Kill switch on thread 2: alive
Kill switch on thread 1: alive
Kill switch on thread 2: alive
Kill switch on thread 1: alive
Flipping kill switch on main thread
Kill switch on thread 2: killed
Kill switch on thread 1: killed
Kill switch on thread 1: killed
Thread 1 wrapping up
Kill switch on thread 2: killed
Thread 2 wrapping up
All threads finished
Structs§
- Kill
Switch - Convenience type which wraps a
AtomicBool
. Initially,is_alive()
will returntrue
. The value can be cloned across threads, and once it has beenkill()
ed, then all of the clones will returnfalse
fromis_alive()
. - Kill
Switch Watcher - Derived from a
KillSwitch
, allows to check if the kill switch is still alive, but cannot activate it. This may be useful in separating out a thread which is only watching the value of the kill switch.
Enums§
- Kill
Switch Err - General error type for a
KillSwitch