Thread control in python – how to safely stop a thread

So you want to kill a thread… Why not ask the thread to stop instead?
burmese_python_125x125
Of course it’s unsafe to just kill a thread dead in its tracks. What if the thread has some resource acquired or is controlling other threads itself? It’s much better to communicate with a thread and tell it to stop, then just wait for it to kill itself.

class MyThread(threading.Thread):
    def __init__(self, filename, queue):
        threading.Thread.__init__(self)
        self.fn = filename
        self.q = queue
        self.stop = threading.Event()

    def stop(self):
        self.stop.set()

    def stopped(self):
        return self.stop.isSet()

    def run(self):
        item = self.q.get()
        while not self.stopped():
            f = open(self.fn, 'w')
            f.write('.')
            sleep(30)
            f.close()
        self.queue.task_done()

Now you can queue up some MyThreads and if you want to stop a thread, just call that particular thread’s stop method and wait for it to finish its current cycle. In my example, each MyThread checks its status at the beginning of each loop while it’s running.

As long as you remember to make the threads check the status while running and call self.queue.task_done() if they are asked to stop, then waiting for a join shouldn’t cause a problem. You can give join a timeout value and forcibly stop the thread if it doesn’t respond in time. In this case, it should be checking the status about every 30 seconds.

Remember, this is just a made up example to show that some cleanup needs to happen before the thread actually dies in a fire. But imagine for a second that you just killed the thread instead of asking it to kill itself, what would happen to the open file? Would it clean up itself? I guess that depends, but implementing a way for the thread to stop itself is definitely the safest choice.

Posted by admica   @   20 June 2011

Related Posts

0 Comments

No comments yet. Be the first to leave a comment !
Leave a Comment

Name

Email

Website

*

Previous Post
«
Next Post
»
Powered by Wordpress   |   Lunated designed by ZenVerse

Valid XHTML 1.0 Transitional