Crate killswitch

Source
Expand description

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.

Modules§

pair
The paired killswitch is separated into a KillTrig (used to trigger a shutdown notification) and a KillWait (used to wait for the killswitch to be triggered).

Structs§

FinalizedFuture
Used to wait for all waiters to deregister.
KillSwitch
The KillSwitch is used both to signal termination and waiting for termination.
WaitFuture
A future used to wait for a KillSwitch to become triggered.