Kill a thread in Python

Peter Hansen peter at engcorp.com
Tue May 4 07:26:25 EDT 2004


C. Barnes wrote:

> This code module allows you to kill threads.  The
> class KThread is a drop-in replacement for
> threading.Thread.  It adds the kill() method, which
> should stop most threads in their tracks.

>   def __run(self):
>     """Hacked run function, which installs the
> trace."""
>     sys.settrace(self.globaltrace)
>     self.__run_backup()
>     self.run = self.__run_backup

Although I'm usually against premature optimization, in this
case I have to point out the potentially *very* significant
impact of using the system tracing capability...

Also, this sort of "kill" is easily implemented on a special
case basis in real code, where you generally just want to check
at a high level whether the thread has been requested to die.
Doing it at each bytecode seems like overkill, unless you
tend to write lots of potentially endless loops at lower levels.

Having a thread stuck in external code is by far the most common
use case for this, I think, which this won't handle.

It's a nice example of a use of sys.settrace, however...

-Peter



More information about the Python-list mailing list