Crate killswitch[][src]

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

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

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

  tokio::spawn(croakable(String::from("test1"), shutdown.clone()));
  tokio::spawn(croakable(String::from("test2"), shutdown.clone()));

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

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

  tokio::spawn(croakable(String::from("test3"), shutdown.clone()));
  tokio::spawn(croakable(String::from("test4"), shutdown));

  // Wait for all associated shutdown objects to become inactive.
  killswitch.await;

  Ok(())
}

async fn croakable(s: String, shutdown: Shutdown) {
  println!("croakable({}) entered", s);
  shutdown.wait().await;
  println!("croakable({}) leaving", s);
}

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

Structs

KillSwitch

The kill switch used to signal that tasks should self-terminate.

Shutdown

Receiver object for kill switches.

ShutdownFuture

Future returned by Shutdown::wait().

Functions

killswitch

Create a connected KillSwitch and a Shutdown pair.