Skip to content

Commit

Permalink
Merge pull request #275 from labthings/release-locks-on-error
Browse files Browse the repository at this point in the history
Release locks on error
  • Loading branch information
rwb27 authored Aug 23, 2021
2 parents cdeb2d0 + 7151372 commit 2ef7a8d
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 6 deletions.
16 changes: 10 additions & 6 deletions src/labthings/sync/lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,11 @@ def _owner(self):
@contextmanager
def __call__(self, timeout=sentinel, blocking: bool = True):
result = self.acquire(timeout=timeout, blocking=blocking)
yield result
if result:
self.release()
try:
yield result
finally:
if result:
self.release()

def locked(self):
""" """
Expand Down Expand Up @@ -122,9 +124,11 @@ def _owner(self):
@contextmanager
def __call__(self, timeout=sentinel, blocking: bool = True):
result = self.acquire(timeout=timeout, blocking=blocking)
yield result
if result:
self.release()
try:
yield result
finally:
if result:
self.release()

def acquire(self, blocking: bool = True, timeout=sentinel):
"""
Expand Down
30 changes: 30 additions & 0 deletions tests/test_sync_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,33 @@ def g():
with pytest.raises(lock.LockError):
with this_lock(timeout=0.01):
pass

class DummyException(Exception):
pass

def test_rlock_released_after_error_args(this_lock):
"""If an exception occurs in a with block, the lock should release.
NB there are two sets of code that do this - one if arguments are
given (i.e. the __call__ method of the lock class) and one without
arguments (i.e. the __enter__ and __exit__ methods).
See the following function for the no-arguments version.
"""
try:
with this_lock():
assert this_lock.locked()
raise DummyException()
except DummyException:
pass
assert not this_lock.locked()

def test_rlock_released_after_error_noargs(this_lock):
"""If an exception occurs in a with block, the lock should release."""
try:
with this_lock:
assert this_lock.locked()
raise DummyException()
except DummyException:
pass
assert not this_lock.locked()

0 comments on commit 2ef7a8d

Please sign in to comment.