killswitch

Killswitch used to broadcast a shutdown request

5 unstable releases

0.4.2 Sep 17, 2023
0.4.1 Sep 6, 2023
0.4.0 Sep 8, 2022
0.3.0 Aug 10, 2021
0.1.1 Mar 2, 2021

#453 in Asynchronous

Download history 9/week @ 2024-06-17 12/week @ 2024-06-24 7/week @ 2024-07-15 8/week @ 2024-07-22 1/week @ 2024-07-29 7/week @ 2024-08-05 4/week @ 2024-08-12 7/week @ 2024-08-19 25/week @ 2024-08-26 13/week @ 2024-09-09 15/week @ 2024-09-16 40/week @ 2024-09-23 19/week @ 2024-09-30

87 downloads per month
Used in 8 crates (6 directly)

0BSD license

19KB
316 lines

killswitch

A killswitch is a special-purpose channel-like object used to signal to tasks that they should terminate.


lib.rs:

This library provides two separate structures for signalling (and receiveing) termination requests [in async contexts]:

KillSwitch

Signal a request for (multiple) async tasks to self-terminate.

use std::error::Error;
use tokio::time::{sleep, Duration};
use killswitch::KillSwitch;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
  let ks = KillSwitch::new();

  tokio::spawn(killable(String::from("test1"), ks.clone()));
  tokio::spawn(killable(String::from("test2"), ks.clone()));

  sleep(Duration::from_secs(1)).await;

  println!("Triggering kill switch");
  ks.trigger();

  tokio::spawn(killable(String::from("test3"), ks.clone()));
  tokio::spawn(killable(String::from("test4"), ks.clone()));

  // Wait for all waiters to drop
  ks.finalize().await;

  Ok(())
}

async fn killable(s: String, ks: KillSwitch) {
  println!("killable({}) entered", s);
  ks.wait().await;
  println!("killable({}) leaving", s);
}

killswitch was developed to help create abortable async tasks in conjuction with multiple-wait features such as the tokio::select! macro.

Dependencies

~0.4–5MB
~11K SLoC