Threading-> Stopping

Antoon Pardon apardon at forel.vub.ac.be
Mon Nov 7 14:27:12 CET 2005


Op 2005-11-04, Tuvas schreef <tuvas21 at gmail.com>:
> Is there a way to stop a thread with some command like t.stop()? Or any
> other neat way to get around it? Thanks!

What do you mean with stop? Pauze it or make it finish.

In the latter case, if you really want it you could use the following.
It requires ctypes. It also wont stop a thread while it is in a C
extention. In that case the exception will be raised when it returns
from the extention.

import os
import ctypes
from time import sleep
from random import randint


class TimeOut(Exception):
  pass

class Alarm(Exception):
  pass

import threading

class Xthread(threading.Thread):
    
  def start(self):
    self.__original_run = self.run
    self.run = self.__run 
    threading.Thread.start(self)

  def __run(self):
    self.__thrd_id = threading._get_ident()
    try:
      self.__original_run()
    finally:
      self.run = self.__original_run

  def raize(self, excpt):
    Nr = ctypes.pythonapi.PyThreadState_SetAsyncExc(self.__thrd_id, ctypes.py_object(excpt))
    while Nr > 1:
      ctypes.pythonapi.PyThreadState_SetAsyncExc(self.__thrd_id, None)
      sleep(0.1)
      Nr = ctypes.pythonapi.PyThreadState_SetAsyncExc(self.__thrd_id, ctypes.py_object(excpt))

  def alarm(self, tm):
    alrm = threading.Timer(tm, self.raize, (TimeOut,))
    alrm.start()
    return alrm

if __name__ == "__main__":

  class Continue(Xthread):
  
    def run(self):
  
      self.id = os.getpid()
      print self.id, "Begin"
      i = 0
      try:
        for _ in xrange(randint(0,20)):
          for e in xrange(4 * 100000):
      i = i + e
        print self.id, "Finished"
      except Alarm:
        print self.id, "Interupted"
  
  lst = [Continue() for _ in xrange(10)]
  
  for T in lst:
    T.start()
  
  try:
    sleep(10)
  finally:
    for T in lst:
      T.raize(Alarm)



More information about the Python-list mailing list