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;
let kill = KillSwitch::default();
println!("Is kill switch set? {}", kill);
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");
});
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