Oct-17-2020, 12:33 PM
(Oct-17-2020, 06:04 AM)Gribouillis Wrote: There are still things to try. You could callqueue.close()
andqueue.join_thread()
in the worker process when it receives the instruction to stop. This would wait until every data previously sent to the queue has been written in the underlying pipe. Also it would raise an exception if the run() function still tries to put() anything else in the queue.
This solution works
from multiprocessing import Process, Lock from threading import Thread from time import sleep from sys import exit from multiprocessing import Queue class Worker(Process): def __init__(self, queue: Queue): Process.__init__(self) self.queue = queue def run(self): i = 0 try: while True: self.queue.put(i) i += 1 except ValueError: pass def stop(self): self.queue.put("END") self.queue.close() self.queue.join_thread() self.terminate() class Listener(Thread): def __init__(self): Thread.__init__(self) self.queue = Queue() self.worker = Worker(self.queue) self.is_running = True def run(self): self.worker.start() while self.is_running: try: data = self.queue.get() if data != "END": pass else: self.is_running = False except TypeError: self.is_running = False def stop(self): self.worker.stop() self.is_running = False class System: def __init__(self): self.listener = Listener() def start(self): self.listener.start() def stop(self): self.listener.stop() if __name__ == "__main__": system = System() system.start() sleep(0.1) system.stop() sleep(1) print(f"Process Alive: {system.listener.worker.is_alive()}") print(f"Thread Alive: {system.listener.is_alive()}")