import threading
import time
import inspect
import ctypes
class ThreadEx(threading.Thread):
func = None
def run(self):
if self.func:
self.func()
def _async_raise(self, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(self.ident)
if not 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")
def stop_thread(self):
self._async_raise(SystemExit)
def test():
i = 0
while True:
i+=1
print(i)
time.sleep(0.1)
if __name__ == "__main__":
t = ThreadEx()
t.func = test
t.start()
time.sleep(0.5)
t.stop_thread()
time.sleep(10)
print("stoped")
网上淘来的的有没有更简单的强行终止线程的方法
求大佬指点