50 lines
2.0 KiB
Python
50 lines
2.0 KiB
Python
"""Cooperative FIFO admission for this application's native operations."""
|
|
from threading import Condition
|
|
|
|
|
|
class QueueCancelled(RuntimeError):
|
|
pass
|
|
|
|
|
|
class NativeQueue:
|
|
def __init__(self):
|
|
self.condition = Condition()
|
|
self.pending = []
|
|
self.active = False
|
|
|
|
def wake(self):
|
|
with self.condition: self.condition.notify_all()
|
|
|
|
def run(self, action, *, stop=None, waiting=None, ready=lambda: True, wait_state=None):
|
|
ticket = object()
|
|
acquired, notified = False, False
|
|
previous_state = None
|
|
with self.condition: self.pending.append((ticket, ready))
|
|
try:
|
|
while not acquired:
|
|
with self.condition:
|
|
if stop is not None and stop.is_set():
|
|
raise QueueCancelled('已取消排队,未启动原生操作。')
|
|
first = next((token for token, available in self.pending if available()), None)
|
|
if not self.active and first is ticket:
|
|
self.pending = [entry for entry in self.pending if entry[0] is not ticket]
|
|
self.active = acquired = True
|
|
else:
|
|
self.condition.wait(.1)
|
|
if not acquired and waiting is not None:
|
|
try:
|
|
current_state = wait_state() if wait_state is not None else None
|
|
if not notified or current_state != previous_state:
|
|
waiting()
|
|
notified, previous_state = True, current_state
|
|
except Exception:
|
|
pass
|
|
if stop is not None and stop.is_set():
|
|
raise QueueCancelled('已取消排队,未启动原生操作。')
|
|
return action()
|
|
finally:
|
|
with self.condition:
|
|
self.pending = [entry for entry in self.pending if entry[0] is not ticket]
|
|
if acquired: self.active = False
|
|
self.condition.notify_all()
|