diff --git a/can/thread_safe_bus.py b/can/thread_safe_bus.py index 518604364..04633a7c3 100644 --- a/can/thread_safe_bus.py +++ b/can/thread_safe_bus.py @@ -107,8 +107,9 @@ def shutdown(self) -> None: @property def state(self) -> BusState: - with self._self_lock_send, self._self_lock_recv: - return self._self_wrapped.state + # Reading the state must not wait for the locks: a thread blocking in + # recv() holds the receive lock for its whole timeout. + return self._self_wrapped.state @state.setter def state(self, new_state: BusState) -> None: @@ -117,5 +118,4 @@ def state(self, new_state: BusState) -> None: @property def protocol(self) -> CanProtocol: - with self._self_lock_send, self._self_lock_recv: - return self._self_wrapped.protocol + return self._self_wrapped.protocol diff --git a/doc/changelog.d/1891.fixed.rst b/doc/changelog.d/1891.fixed.rst new file mode 100644 index 000000000..3a1845985 --- /dev/null +++ b/doc/changelog.d/1891.fixed.rst @@ -0,0 +1 @@ +Reading ``ThreadSafeBus.state`` and ``ThreadSafeBus.protocol`` no longer waits for a thread that is blocked in ``recv()``. diff --git a/test/back2back_test.py b/test/back2back_test.py index b82e89b27..4b448d9ad 100644 --- a/test/back2back_test.py +++ b/test/back2back_test.py @@ -426,6 +426,20 @@ def receiver(_): receiver_pool.close() receiver_pool.join() + def test_state_while_recv_blocks(self): + """Reading state and protocol does not wait for a blocked recv() (#1891).""" + receiver = ThreadPool(1) + pending = receiver.apply_async(self.bus2.recv, (1.0,)) + sleep(0.1) # let the receiver take the receive lock + + start = time() + self.assertIsInstance(self.bus2.state, can.BusState) + self.assertIsInstance(self.bus2.protocol, can.CanProtocol) + self.assertLess(time() - start, 0.5) + + self.assertIsNone(pending.get()) + receiver.close() + @pytest.mark.timeout(180.0 if IS_PYPY else 5.0) def test_filtered_bus(self): sender_pool = ThreadPool(100)