From bcd9827c3b845f357ff5a3dab19b02ba88617c44 Mon Sep 17 00:00:00 2001 From: David Wilson Date: Sat, 19 Jan 2019 22:23:31 +0000 Subject: [PATCH] core: Latch.empty() improvements - throw LatchError if the latch is closed. - wrap with the lock to avoid unexpected weirdness. --- mitogen/core.py | 14 ++++++++++++-- tests/latch_test.py | 7 +++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/mitogen/core.py b/mitogen/core.py index fb182e3c..8c03145f 100644 --- a/mitogen/core.py +++ b/mitogen/core.py @@ -742,7 +742,8 @@ class Sender(object): self.context.send( Message.dead( reason=self.explicit_close_msg, - handle=self.dst_handle) + handle=self.dst_handle + ) ) def __repr__(self): @@ -1884,8 +1885,17 @@ class Latch(object): though a subsequent call to :meth:`get` will block, since another waiting thread may be woken at any moment between :meth:`empty` and :meth:`get`. + + :raises LatchError: + The latch has already been marked closed. """ - return len(self._queue) == 0 + self._lock.acquire() + try: + if self.closed: + raise LatchError() + return len(self._queue) == 0 + finally: + self._lock.release() def _get_socketpair(self): """ diff --git a/tests/latch_test.py b/tests/latch_test.py index 5be12d73..6ae43221 100644 --- a/tests/latch_test.py +++ b/tests/latch_test.py @@ -21,6 +21,13 @@ class EmptyTest(testlib.TestCase): latch.put(None) self.assertTrue(not latch.empty()) + def test_closed_is_empty(self): + latch = self.klass() + latch.put(None) + latch.close() + self.assertRaises(mitogen.core.LatchError, + lambda: latch.empty()) + class GetTest(testlib.TestCase): klass = mitogen.core.Latch