Skip to content

Commit d4b1d79

Browse files
author
Joel Collins
committed
2 parents e021369 + 2bef01b commit d4b1d79

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/labthings/core/lock.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from gevent.hub import getcurrent
22
from gevent.lock import RLock as _RLock
33

4+
from contextlib import contextmanager
45
import logging
56

67
from .exceptions import LockError
@@ -31,6 +32,13 @@ def __init__(self, timeout=None, name=None):
3132
self.timeout = timeout
3233
self.name = name
3334

35+
@contextmanager
36+
def __call__(self, timeout=sentinel, blocking=True):
37+
result = self.acquire(timeout=timeout, blocking=blocking)
38+
yield result
39+
if result:
40+
self.release()
41+
3442
def locked(self):
3543
return self._lock.locked()
3644

@@ -82,6 +90,13 @@ def __init__(self, locks, timeout=None):
8290
self.locks = locks
8391
self.timeout = timeout
8492

93+
@contextmanager
94+
def __call__(self, timeout=sentinel, blocking=True):
95+
result = self.acquire(timeout=timeout, blocking=blocking)
96+
yield result
97+
if result:
98+
self.release()
99+
85100
def acquire(self, blocking=True, timeout=sentinel):
86101
if timeout is sentinel:
87102
timeout = self.timeout

tests/test_core_lock.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,3 +88,26 @@ def test_rlock_block(this_lock):
8888

8989
# Release lock, assert no owner
9090
assert not this_lock._is_owned()
91+
92+
def test_rlock_acquire_timeout(this_lock):
93+
from labthings.core.exceptions import LockError
94+
95+
# Acquire lock
96+
assert this_lock.acquire()
97+
98+
# Override owner to force acquisition failure
99+
this_lock._owner = None
100+
print(this_lock._owner)
101+
# Assert not owner
102+
assert not this_lock._is_owned()
103+
104+
# Assert acquisition fails using context manager
105+
with pytest.raises(LockError):
106+
with this_lock(timeout=0.01):
107+
pass
108+
109+
# Force ownership
110+
this_lock._owner = getcurrent()
111+
112+
# Release lock
113+
this_lock.release()

0 commit comments

Comments
 (0)