Skip to main content

Module preemptive

Module preemptive 

Source
Expand description

Preemptive task cancellation (watchdog + signal-based). See preemptive::PreemptiveCancellationToken and preemptive::with_deadline. Preemptive task cancellation

Extends cooperative cancellation with deadline-driven, signal-driven, and scope-bound preemption. Architecture:

  PreemptiveCancellationToken  ──owns──►  PreemptionState (Arc)
        │                                       │
        │ cancel_after(Duration)                │ cancelled: AtomicBool
        │      │                                │ deadline:  AtomicU64
        │      ▼                                │ waiters:   Condvar
        │  WatchdogThread  ──notify──►  sets cancelled = true
        │
        │ cancel_at(Instant)  ──same path──►  WatchdogThread
        │
        │ [Linux] signal_preempt()  ──pthread_kill──►  SIGUSR2 handler
        │                                             sets AtomicBool
        ▼
  DeadlineGuard  (RAII)  ──drop──►  if elapsed ≥ budget → cancel()

§Usage

use taskflow_rs::preemptive::{PreemptiveCancellationToken, DeadlineGuard};
use std::time::Duration;

let token = PreemptiveCancellationToken::new();

// Option 1 – automatic watchdog timeout
token.cancel_after(Duration::from_millis(500));

// Option 2 – RAII deadline guard
let guard = token.deadline_guard(Duration::from_millis(500));

// Inside the task:
for chunk in data.chunks(1024) {
    token.check()?;          // returns Err(Preempted) if cancelled
    process(chunk);
}

Structs§

DeadlineGuard
RAII guard that automatically cancels a token when dropped (if the budget has elapsed). Useful for lexically scoped time budgets:
Preempted
Returned by PreemptiveCancellationToken::check() when the task has been preempted.
PreemptiveCancellationToken
Preemptive cancellation token.

Functions§

with_deadline
Run a closure with a time budget. Returns Err(Preempted) if the token was cancelled before the closure finishes. The closure itself decides how frequently it polls token.check().