#switch #kill #standard #thread-safe #std #killswitch #kill-switch

killswitch_std

A thread-safe kill switch using only the standard library

7 releases

new 0.3.1 Jan 10, 2025
0.3.0 Jan 7, 2025
0.2.4 Jan 6, 2025

#533 in Concurrency

Download history 248/week @ 2025-01-01 161/week @ 2025-01-08

409 downloads per month

AGPL-3.0-only

16KB
87 lines

killswitch_std

Crates.io Documentation Build status License

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

No runtime deps