"""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): ticket = object() acquired, notified = False, False 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 not notified and waiting is not None: notified = True try: waiting() 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()