diff --git a/multidongle.py b/multidongle.py index 905dc2a..983cfaf 100644 --- a/multidongle.py +++ b/multidongle.py @@ -325,31 +325,29 @@ class MultiDongle: # print("Threads stopped.") def stop(self): - """ - Stop inference threads cleanly - """ + """Improved stop method with better cleanup""" + if self._stop_event.is_set(): + return # Already stopping + print("Stopping threads...") self._stop_event.set() - # Unblock send thread if waiting on queue - try: - self._input_queue.put(None, timeout=1.0) - except: - pass + # Clear queues to unblock threads + while not self._input_queue.empty(): + try: + self._input_queue.get_nowait() + except queue.Empty: + break - # Join threads with reasonable timeout - threads = [ - (self._send_thread, "Send thread"), - (self._receive_thread, "Receive thread") - ] + # Signal send thread to wake up + self._input_queue.put(None) - for thread, name in threads: + # Join threads with timeout + for thread, name in [(self._send_thread, "Send"), (self._receive_thread, "Receive")]: if thread and thread.is_alive(): - thread.join(timeout=3.0) + thread.join(timeout=2.0) if thread.is_alive(): - print(f"Warning: {name} did not stop within timeout") - - print("All threads stopped") + print(f"Warning: {name} thread didn't stop cleanly") def put_input(self, image: Union[str, np.ndarray], format: str, target_size: Tuple[int, int] = None): """