Op 2005-11-04, Tuvas schreef <tu*****@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(Excepti on):
pass
class Alarm(Exception ):
pass
import threading
class Xthread(threadi ng.Thread):
def start(self):
self.__original _run = self.run
self.run = self.__run
threading.Threa d.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.pythonap i.PyThreadState _SetAsyncExc(se lf.__thrd_id, ctypes.py_objec t(excpt))
while Nr > 1:
ctypes.pythonap i.PyThreadState _SetAsyncExc(se lf.__thrd_id, None)
sleep(0.1)
Nr = ctypes.pythonap i.PyThreadState _SetAsyncExc(se lf.__thrd_id, ctypes.py_objec t(excpt))
def alarm(self, tm):
alrm = threading.Timer (tm, self.raize, (TimeOut,))
alrm.start()
return alrm
if __name__ == "__main__":
class Continue(Xthrea d):
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)