方法一:强制杀死
import threading
import time
import inspect
import ctypes
def _async_raise(tid, exctype):
if not inspect.isclass(exctype):
raise TypeError("Only types can be raised (not instances)")
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
_async_raise(thread.ident, SystemExit)
class TestThread(threading.Thread):
def run(self):
print("begin run the child thread")
while True:
print("sleep 1s")
time.sleep(1)
if __name__ == "__main__":
print("begin run main thread")
t = TestThread()
t.start()
time.sleep(3)
stop_thread(t)
print("main thread end")
方法二:优雅杀死
# encoding:utf-8
import time
import threading
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self, *args, **kwargs):
super(StoppableThread, self).__init__(*args, **kwargs)
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
def run(self):
print("begin run the child thread")
while True:
print("sleep 1s")
time.sleep(1)
if self.stopped():
# 做一些必要的收尾工作
break
if __name__ == "__main__":
print("begin run main thread")
t = StoppableThread()
t.start()
time.sleep(3)
t.stop()
print("main thread end")
方法一改动:
def stop_thread(self):
try:
for i in range(3):
self._async_raise(self._receive_thread.ident, SystemExit)
time.sleep(1)
except Exception as e:
logger.info(f"线程终止异常:{e}")
方法二,重点在于在线程函数中通过信号传递,使用break退出函数
if self.stopped(): break
通过下面的函数查看线程状态,是否被杀死
def state(self):
status = my_thread.is_alive()
# my_thread 是threading.Thread创建的线程对象
logger.info(f'线程状态: {status}')
return status