看了一大堆没用的教程,最终自己实现
原理就是调用ctype模块,代码如下
import ctypes
def kill_thread(inner_work_thread):
if not inner_work_thread.is_alive():
return
# 终止线程
async_exc = ctypes.py_object(SystemExit)
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(inner_work_thread.ident), async_exc)
然后讲你的线程方法传入即可。但是会存在一些泄露的问题,原理自己去找吧
完整如下
from threading import Thread
from time import sleep
import ctypes
def kill_thread(inner_work_thread):
if not inner_work_thread.is_alive():
return
# 终止线程
async_exc = ctypes.py_object(SystemExit)
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(inner_work_thread.ident), async_exc)
def fun():
print(555)
sleep(2)
print(6666)
t1=Thread(target=fun)
t1.start()
kill_thread(t1)