Skip navigation.

Python - Terminating Threads - Boolean Flag and threading.Event()

Python - Terminating Threads - Boolean Flag and threading.Event()

In many programming languages you can't terminate a thread directly.  Python is no different.  Rather than termintaing a thread from the code that spawned it, you just a pass a flag to the thread that tells it to terminate itself.  Typically a thread will run in a loop, periodically checking this flag so it knows if it should continue or not.  To terminate the thread from the outside, you just set its flag to die.

I was using this idiom in Python by setting a boolean flag in my spawned thread.

So a simplified thread class would look something like this:

 class MyThread(threading.Thread): def __init__(self,
num): threading.Thread.__init__(self) self.running = True self.num = num def stop(self):
self.running = False def run(self): while self.running: print 'hello from thread %d'
% self.num time.sleep(1) 

I just read an old post in comp.lang.python that pointed to a recipe in the Python Cookbook that suggests using threading.Event() rather than a simple boolean flag.

So the thread class would look something like this:

 class MyThread(threading.Thread): def __init__(self,
num): threading.Thread.__init__(self) self.stop_event = threading.Event() self.num
= num def stop(self): self.stop_event.set() def run(self): while not self.stop_event.isSet():
print 'hello from thread %d' % self.num time.sleep(1) 

They work exactly the same.

I am just wondering what other flexibility threading.Event() gives you, and if there is anything bad about using simple boolean checks to kill threads. I guess I will have to look it up and play around a bit.