|
1 | | -import heapq |
| 1 | +from queue import PriorityQueue |
| 2 | +from queue import Queue |
2 | 3 | from threading import Lock |
3 | 4 | from typing import TYPE_CHECKING |
4 | 5 | from weakref import proxy |
|
15 | 16 |
|
16 | 17 | class BaseEngine: |
17 | 18 | def __init__(self, sm: "StateMachine", rtc: bool = True): |
18 | | - self.sm: StateMachine = proxy(sm) |
19 | | - self._external_queue: list = [] |
20 | 19 | self._sentinel = object() |
21 | 20 | self._rtc = rtc |
22 | | - self._processing = Lock() |
23 | 21 | self._running = True |
| 22 | + self._init(sm) |
| 23 | + |
| 24 | + def _init(self, sm: "StateMachine"): |
| 25 | + self.sm: StateMachine = proxy(sm) |
| 26 | + self._external_queue: Queue = PriorityQueue() |
| 27 | + self._processing = Lock() |
| 28 | + |
| 29 | + def __getstate__(self) -> dict: |
| 30 | + state = self.__dict__.copy() |
| 31 | + del state["_external_queue"] |
| 32 | + del state["_processing"] |
| 33 | + del state["sm"] |
| 34 | + return state |
| 35 | + |
| 36 | + def __setstate__(self, state: dict) -> None: |
| 37 | + for attr, value in state.items(): |
| 38 | + setattr(self, attr, value) |
| 39 | + |
| 40 | + def empty(self): |
| 41 | + return self._external_queue.qsize() == 0 |
24 | 42 |
|
25 | 43 | def put(self, trigger_data: TriggerData): |
26 | 44 | """Put the trigger on the queue without blocking the caller.""" |
27 | 45 | if not self._running and not self.sm.allow_event_without_transition: |
28 | 46 | raise TransitionNotAllowed(trigger_data.event, self.sm.current_state) |
29 | 47 |
|
30 | | - heapq.heappush(self._external_queue, trigger_data) |
| 48 | + self._external_queue.put(trigger_data) |
| 49 | + |
| 50 | + def pop(self): |
| 51 | + try: |
| 52 | + return self._external_queue.get(block=False) |
| 53 | + except Exception: |
| 54 | + return None |
| 55 | + |
| 56 | + def clear(self): |
| 57 | + with self._external_queue.mutex: |
| 58 | + self._external_queue.queue.clear() |
31 | 59 |
|
32 | 60 | def start(self): |
33 | 61 | if self.sm.current_state_value is not None: |
|
0 commit comments