Coverage for /Users/eugene/Development/legion-utils/legion_utils/utils.py: 0%

1 from contextlib import contextmanager

2 from threading import Lock

3 from typing import ContextManager

4

5

6 class ReadWriteLock:

7 def __init__(self):

8 self._r_lock = Lock()

9 self._rw_lock = Lock()

10 self._num_read = 0

11

12 def _acquire_read(self) -> None:

13 with self._r_lock:

14 self._num_read += 1

15 if self._num_read == 1:

16 self._rw_lock.acquire()

17

18 def _release_read(self) -> None:

19 with self._r_lock:

20 if self._num_read <= 0:

21 raise RuntimeError("Attempted to release read-lock without holding it")

22 self._num_read -= 1

23 if self._num_read == 0:

24 self._rw_lock.release()

25

26 @contextmanager

27 def read(self) -> ContextManager[None]:

28 try:

29 self._acquire_read()

30 yield

31 finally:

32 self._release_read()

33

34 @contextmanager

35 def write(self) -> ContextManager[None]:

36 try:

37 self._rw_lock.acquire()

38 yield

39 finally:

40 self._rw_lock.release()

41