stemdeck-gpu / stemdeck /gpulock.py
AnjaneyaTurai's picture
Deploy the StemDeck GPU service
25e4412 verified
Raw History Blame Contribute Delete
2.38 kB
"""One GPU job at a time across every StemDeck server on this computer.
Each server's job runner already runs one job at a time, but the public site can run from this PC next to your
own StemDeck (two servers, one 4 GB GPU). A worker therefore holds an exclusive OS lock on a shared file while it
works. The OS drops the lock when the process ends, so a crashed or killed worker never leaves the GPU "taken".
"""
from __future__ import annotations
import sys
import time
from collections.abc import Callable
from pathlib import Path
from typing import IO
POLL_SEC = 2.0
class GpuLock:
def __init__(self, path: Path) -> None:
self.path = path
self._file: IO[bytes] | None = None
def try_acquire(self) -> bool:
"""Take the lock if it is free. True when this process now holds it."""
if self._file is not None:
return True
self.path.parent.mkdir(parents=True, exist_ok=True)
handle = open(self.path, "a+b") # noqa: SIM115 - kept open for as long as the lock is held
try:
_lock(handle)
except OSError:
handle.close()
return False
self._file = handle
return True
def acquire(self, on_wait: Callable[[], None] | None = None, poll_sec: float = POLL_SEC) -> None:
"""Wait until the lock is free and take it. `on_wait` is called once if another worker holds it."""
if self.try_acquire():
return
if on_wait is not None:
on_wait()
while not self.try_acquire():
time.sleep(poll_sec)
def release(self) -> None:
if self._file is None:
return
try:
_unlock(self._file)
finally:
self._file.close()
self._file = None
if sys.platform == "win32":
import msvcrt
def _lock(handle: IO[bytes]) -> None:
handle.seek(0)
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1) # raises OSError when another process holds it
def _unlock(handle: IO[bytes]) -> None:
handle.seek(0)
msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
else:
import fcntl
def _lock(handle: IO[bytes]) -> None:
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
def _unlock(handle: IO[bytes]) -> None:
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)