Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Terminating threads in Python using threading.Event in a class

$
0
0

I have a Python program that uses fairly long-lived synchronous calls so things are wrapped in threads. Here's a rough MVP:

class MyClass:    processor = None    def __init__(self):        self.processor_active = threading.Event()        self.processor_thread = threading.Thread(target=self.start_processing_thread, daemon=True)        self.processor_thread.start()        self.processor_active.wait()    def start_processing_thread(self):        self.processor = MyProcessor() # this line takes a while to run        self.processor_active.set() # allows the constructor to release        while self.processor_active.is_set():            data = processor.process() # this line can take arbitrarily long to execute            print(f"Received data: {data}")    def shutdown(self):        self.processor.shutdown() # to clean up resources        self.processor_active.clear()        self.processor_thread.join()

My problem: calling shutdown on a MyClass instance hangs forever without shutting down, or it prints "Received data: " repeatedly. It seems my thread cannot get the current state of the threading Event. How do I fix it?


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>