boolean flag vs threading.Event

Chris Mellon arkanes at gmail.com
Tue Feb 27 17:04:51 EST 2007


On 27 Feb 2007 13:37:12 -0800, Daniel <millerdev at gmail.com> wrote:
> I have a class similar to this:
>
>
> class MyThread(threading.Thread):
>
>     def __init__(self):
>         self.terminated = False
>
>     def run(self):
>         while not self.terminated:
>             pass # do stuff here
>
>     def join(self):
>         self.terminated = True
>         threading.Thread.join(self)
>
>
> Recently I was reading in the Python Cookbook (9.2 Terminating a
> Thread) about how to do this sort of thing. That recipe uses a
> threading.Event object to signal the thread termination. Here's my
> class recoded to use an event:
>
>
> class MyThread(threading.Thread):
>
>     def __init__(self):
>         self.event = threading.Event()
>
>     def run(self):
>         while not self.event.isSet():
>             pass # do stuff here
>
>     def join(self):
>         self.event.set()
>         threading.Thread.join(self)
>
>
> If I understand the GIL correctly, it synchronizes all access to
> Python data structures (such as my boolean 'terminated' flag). If that
> is the case, why bother using threading.Event for this purpose?
>


The GIL is an implementation detail and relying on it to synchronize
things for you isn't futureproof. You're likely to have lots of
warning, but using threading.Event() isn't any harder, and it's more
correct and safer in the long term.

There's a whole bunch of other cases where you might want to use an
event, too. For example, you can have a single event which signals
multiple threads to stop, and you can wait on a thread without busy
looping.

If you don't care about doing any of those things, and you're
confident in relying on undocumented features of the GIL to protect
you, and you'll never port your code to a different Python
implementation, then I guess you can go ahead and use the boolean. But
what are you gaining, really?



More information about the Python-list mailing list