File size: 2,375 Bytes
25e4412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""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)