boolean flag vs threading.Event

Daniel millerdev at gmail.com
Tue Feb 27 16:37:12 EST 2007


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?

Thanks,
~ Daniel




More information about the Python-list mailing list