you're reading...
Python, Source Code, Technology

Python – Terminating Threads

According to me Thread management in any language is a messy affair and probably there are a lot of examples that I have come across that illustrates how to terminate threads. Here is a very good and clean example of how to terminate threads from the main (Parent)

import threading
import time

class ThreadExit(threading.Thread):
    def __init__(self):
        self._stopevent = threading.Event()
        self._sleepperiod = 1.0
        threading.Thread.__init__(self, name="ThreadExit")

    def run(self):
        print "%s starts" % (self.getName(),)
        count = 0
        while not self._stopevent.isSet():
            count += 1
            print "loop %d" % (count,)
        print "%s ends" % (self.getName(),)

    def join(self,timeout=None):
        threading.Thread.join(self, timeout)

if __name__ == "__main__":
    threadExit = ThreadExit()

The program also illustrates a very nice approach of overriding the join method to facilitate the termination



No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: