import threading
import sys, os, time
import inspect
import ctypes
import thread
defTestThreadExit():print"Start Now"
Thrd = threading.Thread(target=ThrdMointor)
Thrd.start()print"Start Thrd now "
time_counter =10while time_counter >0:print"timer = "+str(time_counter)+"\n"
time_counter = time_counter -1if time_counter <=0:if Thrd.isAlive():
stop_thread(Thrd)print"time end..."
time.sleep(1)while Thrd.isAlive():if Thrd.isAlive():
stop_thread(Thrd)print"The Thrd is still alive "else:print"The Thrd is dead."
time.sleep(0.2)
Thrd.join()defThrdMointor():
timeCounter =0whileTrue:print"Test Monitor time counter = "+str(timeCounter)+'\n'
time.sleep(1)
timeCounter +=1def_async_raise(tid, exctype):"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)ifnot inspect.isclass(exctype):
exctype =type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))if res ==0:raise ValueError("invalid thread id")elif res !=1:# """if it returns a number greater than one, you're in trouble,# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,None)raise SystemError("PyThreadState_SetAsyncExc failed")defstop_thread(thread):
_async_raise(thread.ident, SystemExit)if __name__=="__main__":
TestThreadExit()
测试结果显示,发现至少3s才能停止线程
Start Now
Test Monitor time counter = 0
Start Thrd now
timer = 10
Test Monitor time counter = 1
timer = 9
Test Monitor time counter = 2
timer = 8
Test Monitor time counter = 3
timer = 7
Test Monitor time counter = 4
timer = 6
Test Monitor time counter = 5
timer = 5
Test Monitor time counter = 6
timer = 4
Test Monitor time counter = 7
timer = 3
Test Monitor time counter = 8
timer = 2
Test Monitor time counter = 9
timer = 1
time end...
Test Monitor time counter = 10
The Thrd is still alive
The Thrd is still alive
The Thrd is still alive
The Thrd is still alive
The Thrd is still alive
Test Monitor time counter = 11
The Thrd is still alive
The Thrd is still alive
The Thrd is still alive
The Thrd is still alive
The Thrd is still alive
Test Monitor time counter = 12
The Thrd is still alive
The Thrd is still alive
The Thrd is still alive
The Thrd is still alive
The Thrd is still alive
Test Monitor time counter = 13
Process finished with exit code 0