"""The machine's heavy slots: one per 4 CPUs, and at least one, each a file locked with flock that every session on the machine shares.""" import fcntl import os import pathlib import time import typing CPUS_PER_SLOT = 4 # Seconds between tries while every slot is held; a slot frees as its command exits. POLL_SECONDS = 1 def usable_cpus() -> int | None: """The CPUs this process may run on, which an affinity mask can make fewer than the machine's; None where the count is unknown.""" return len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else os.cpu_count() def slot_count(cpus: int | None) -> int: return max(1, (cpus or 0) // CPUS_PER_SLOT) def slot_folder(env: typing.Mapping[str, str]) -> pathlib.Path: state = env.get("XDG_STATE_HOME") or str(pathlib.Path.home() / ".local" / "state") return pathlib.Path(state) / "run-heavy" def taken_slot(folder: pathlib.Path, slots: int) -> tuple[int, int] | None: """The number and open file of a slot this call locked; None while every slot is held. Raises OSError where a slot file cannot be opened or locked.""" for slot in range(slots): fd = os.open(folder / f"slot-{slot}", os.O_RDWR | os.O_CREAT, 0o644) try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: os.close(fd) continue except OSError: os.close(fd) raise return slot, fd return None def waited_slot(folder: pathlib.Path, slots: int, say: typing.Callable[[], None], sleep: typing.Callable[[float], None] = time.sleep) -> tuple[int, int]: """The number and open file of a slot this call locked, once one frees. While every slot is held, it calls say once and tries again each POLL_SECONDS.""" said = False while (taken := taken_slot(folder, slots)) is None: if not said: say() said = True sleep(POLL_SECONDS) return taken