Thursday, 5 September 2013

Managing an event loop in a thread

Managing an event loop in a thread

I'm writing a class in a library that has an event processing loop:
class EventSystem(object):
def __init__(self):
self.queue = Queue.Queue()
self.thread = threading.Thread(target=self_process_loop)
self.thread.daemon = True
def _process_loop(self):
while True:
event = self.queue.get()
self._handle_event(event)
def _handle_event(self, event):
...
I've set the thread to be a daemon thread so it exits with the main
program, but this means it could be killed mid-processing. I really want
to wait for the current processing iteration to complete before it is
killed.
Normally in these situations there's a flag being checked in the while
loop and some method - stop(), say - that sets it False. I'd rather avoid
this requirement if at all possible.
Is the following considered bad?
def _process_loop(self):
while True:
event = self.queue.get()
self.thread.daemon = False
self._handle_event(event)
self.thread.daemon = True
What would be the proper way to achieve this?

No comments:

Post a Comment