| 48 | |
| 49 | |
| 50 | class _LocalRwLock: |
| 51 | def __init__(self) -> None: |
| 52 | self._condition = threading.Condition(threading.Lock()) |
| 53 | self._readers = 0 |
| 54 | self._writer = False |
| 55 | |
| 56 | @contextlib.contextmanager |
| 57 | def read(self) -> Iterator[None]: |
| 58 | with self._condition: |
| 59 | while self._writer: |
| 60 | self._condition.wait() |
| 61 | self._readers += 1 |
| 62 | try: |
| 63 | yield |
| 64 | finally: |
| 65 | with self._condition: |
| 66 | self._readers -= 1 |
| 67 | if self._readers == 0: |
| 68 | self._condition.notify_all() |
| 69 | |
| 70 | @contextlib.contextmanager |
| 71 | def write(self) -> Iterator[None]: |
| 72 | with self._condition: |
| 73 | while self._writer or self._readers: |
| 74 | self._condition.wait() |
| 75 | self._writer = True |
| 76 | try: |
| 77 | yield |
| 78 | finally: |
| 79 | with self._condition: |
| 80 | self._writer = False |
| 81 | self._condition.notify_all() |
| 82 | |
| 83 | |
| 84 | def _held_locks() -> dict[Path, tuple[int, int]]: |