How to kill a thread

Peter Hansen peter at engcorp.com
Sun Dec 29 09:41:09 EST 2002


Loet wrote:
> 
> Hello, I'm just starting with Python and I run into something that will be
> documented somwhere, but I just can't find it.
> 
> I guess it must be possible to kill a thread in Python. I think it must
> even be possible by the thread to catch something from other threads with
> the 'try' statement and then have the thread commit suicide. Does anyone
> know how to to this, or know where it's documented?
> 
> Any help would be very much appreciated.

Neither thing you suggest is possible.  There are useful idioms for
at least the first one which you could find easily by searching the
mailing list archives or groups.google.com.

In a nutshell, you must *ask* the thread to terminate, and the thread
must be written in such a way as to check a flag or a signal periodically
to see whether it should do so.  That means it cannot block.  For example,
a server thread should use select.select() in order to be sure of waking
up frequently enough to see that it should terminate in a reasonably
short time after you ask it to.

As for catching exceptions from other threads, that also is not possible,
although you could write a wrapper for the highest level of the thread
(the run() method) which catches all exceptions that are not otherwise
caught, and maybe puts them in a Queue which is read by the main thread.

-Peter



More information about the Python-list mailing list