"""Cooperative cancel for in-process jobs.
The token is polled before each job and before each in-process
dispatch. A force-call inside a compiled relax still runs to the next
poll. ``cancel_state`` sets the flag only while a batch is running,
and the flag is cleared when that batch returns.
"""
from __future__ import annotations
import threading
[docs]
class Cancelled(Exception):
"""Raised when a job sees a cancelled token."""
[docs]
class CancelToken:
def __init__(self) -> None:
self._lock = threading.Lock()
self._cancelled = False
[docs]
def cancel(self) -> None:
with self._lock:
self._cancelled = True
[docs]
def reset(self) -> None:
with self._lock:
self._cancelled = False
@property
def cancelled(self) -> bool:
with self._lock:
return self._cancelled
[docs]
def raise_if_cancelled(self) -> None:
if self.cancelled:
raise Cancelled("job cancelled")