File size: 761 Bytes
5b4c023
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
"""Cooperative cancellation primitives for interruptible robot execution."""

from __future__ import annotations

import threading


class ExecutionInterrupted(RuntimeError):
    """Raised at a safe checkpoint after a newer command supersedes a task."""


class CancellationToken:
    """Thread-safe, dependency-free cancellation token."""

    def __init__(self):
        self._event = threading.Event()
        self.reason = ""

    def request(self, reason: str = "superseded") -> None:
        self.reason = reason
        self._event.set()

    @property
    def requested(self) -> bool:
        return self._event.is_set()

    def checkpoint(self) -> None:
        if self.requested:
            raise ExecutionInterrupted(self.reason or "interrupted")