Killing a thread

crazymykl at crazymykl at
Sat Jun 10 20:58:15 CEST 2006

Fredrik Lundh wrote:
> Carl J. Van Arsdall wrote:
> > Are there any plans in the future to add the capability to kill threads
> > from the outside?
> it cannot be done in a portable way, so that's not very likely.

import sys, trace, threading

class KThread(threading.Thread):
  """A subclass of threading.Thread, with a kill() method."""
  def __init__(self, *args, **keywords):
    threading.Thread.__init__(self, *args, **keywords)
    self.killed = False

  def start(self):
    """Start the thread."""
    self.__run_backup = = self.__run      # Force the Thread to install our trace.

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

  def globaltrace(self, frame, why, arg):
    if why == 'call':
      return self.localtrace
      return None

  def localtrace(self, frame, why, arg):
    if self.killed:
      if why == 'line':
        raise SystemExit()
    return self.localtrace

  def kill(self):
    self.killed = True

More information about the Python-list mailing list