"""The kernel's timers, fired by two threads started with the kernel. A cell can leave the process at its allocation limit (albedo_memory), where a new thread may fail to start, or die before it reports that it started and leave Thread.start() waiting forever. So the kernel starts no thread per cell: each cell's deadline and background timers are alarms on these threads. Deadlines have a thread to themselves. A deadline's action only signals the cell; a background action writes to the daemon, and that write can block while an attached daemon is not reading. No deadline may wait behind it. """ from __future__ import annotations import heapq import itertools import threading import time from collections.abc import Callable class Alarm: """An action run on an alarm thread once armed and due, unless cancelled first; like threading.Timer, arming a cancelled alarm runs nothing.""" def __init__(self, action: Callable[[], object]) -> None: self.action: Callable[[], object] | None = action def cancel(self) -> None: # Dropped now, not when it falls due: it may hold a finished cell. self.action = None class Alarms: """Alarms fired in due order by one thread.""" def __init__(self, name: str) -> None: self.name = name self._due: list[tuple[float, int, Alarm]] = [] self._order = itertools.count() self._changed = threading.Condition() def arm(self, alarm: Alarm, delay: float) -> Alarm: """Runs the alarm `delay` seconds from now; returns it.""" with self._changed: heapq.heappush( self._due, (time.monotonic() + delay, next(self._order), alarm) ) self._changed.notify() return alarm def after(self, delay: float, action: Callable[[], object]) -> Alarm: return self.arm(Alarm(action), delay) def _next(self) -> Alarm: with self._changed: while True: now = time.monotonic() if self._due and self._due[0][0] <= now: return heapq.heappop(self._due)[2] _ = self._changed.wait(self._due[0][0] - now if self._due else None) def _fire(self) -> None: while True: try: action = self._next().action if action is not None: action() except Exception: # An allocation failed at the limit: the thread must outlive it. time.sleep(0.01) def start(self) -> None: threading.Thread(target=self._fire, name=self.name, daemon=True).start() deadlines = Alarms("albedo-deadlines") backgrounds = Alarms("albedo-backgrounds") def start() -> None: """Starts both alarm threads; once, while the kernel boots.""" deadlines.start() backgrounds.start()