Python终止线程的方法
亲测使用如下方法有效,但是如果线程中涉及获取释放锁,可能会导致死锁。
def _async_raise(tid, exctype):
"""
线程退出,这种方法是强制杀死线程,但是如果线程中涉及获取释放锁,可能会导致死锁。
:param tid: thread id
:param exctype: https://docs.python.org/zh-cn/3.8/library/exceptions.html
:return: None
"""
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
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(thread):
"""
线程退出封装方法
:param thread: 线程对象
:return: None
"""
_async_raise(thread.ident, SystemExit)
完整示例代码如下:
import time
import ctypes
import inspect
import threading
def _async_raise(tid, exctype):
"""
线程退出,这种方法是强制杀死线程,但是如果线程中涉及获取释放锁,可能会导致死锁。
:param tid: thread id
:param exctype: https://docs.python.org/zh-cn/3.8/library/exceptions.html
:return: None
"""
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
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(thread):
"""
线程退出封装方法
:param thread: 线程对象
:return: None
"""
_async_raise(thread.ident, SystemExit)
def run():
while True:
print(f"thread id = {threading.current_thread().ident}")
time.sleep(1)
TaskThread = threading.Thread(target=run)
TaskThread.setDaemon(True)
TaskThread.start()
while True:
time.sleep(3)
stop_thread(TaskThread)
TaskThread = threading.Thread(target=run)
TaskThread.setDaemon(True)
TaskThread.start()
运行结果如下图所示
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?