How to get a raised exception from other thread

Peter Hansen peter at engcorp.com
Sun Oct 16 08:33:18 EDT 2005


themightydoyle at gmail.com wrote:
> Nevermind.  I found a better solution.  I used shared memory to create
> a keep-alive flag.  I then use the select function with a specified
> timeout, and recheck the keep-alive flag after each timeout.

As Dennis points out, your original attempt was destined to fail because 
you were calling the method from the main thread, not the one you wanted 
to kill.  Threads don't magically execute any methods that are attached 
to the Thread instance just because they're attached.  You have to 
actually call those methods *from* the thread, which means from the 
run() method or from any of the routines it calls (whether they are 
methods on that Thread or not), but it must be done in the context of 
the thread you want to raise exceptions in or it won't work.

More importantly, you've now described your use case (and I hope that of 
the OP as well, since he hasn't replied yet): killing threads.

This is an oft-discussed topic here, and searching the archives will 
probably give you lots more answers, but the short answer is you cannot 
kill a thread in Python (except by exiting the entire process). Instead, 
as you've discovered, you must ask it nicely to exit.  The nearly 
canonical approach to doing that is as follows:

class MyThread(threading.Thread):
     def __init__(self, *args, **kwargs):
         threading.Thread.__init__(self, *args, **kwargs)
         self._keepRunning = True

     def stop(self, timeout=None):
         self._keepRunning = False
         # optional: wait for thread to exit
         self.join(timeout=timeout)

     def run(self):
         while self._keepRunning:
             # do stuff here

Now you can do things like this:

thread = MyThread()
thread.start()
# other stuff...
thread.stop()    # block here until the thread exits

I hope that clarifies things a little more...

-Peter



More information about the Python-list mailing list