python多线程—终止子线程

总体思路

1、获取需要终止的子线程id
2、根据子线程id,终止子线程。

过程

  • 获取子线程id:
python 复制代码
import threading
Thread_id = threading.get_ident()  # 获取子线程的id值
  • 线程终止函数
python 复制代码
def async_raise(Thread_id, exctype):
    """raises the exception, performs cleanup if needed"""
    tid = ctypes.c_long(Thread_id)
    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")
  • 调用终止函数
python 复制代码
def stop_thread_func():
    async_raise(tid, SystemExit)

转自:https://blog.51cto.com/u_14224/6457768

相关推荐
爱敲代码的小鱼3 分钟前
springsecurity:
java·开发语言·数据库
秋田君5 分钟前
QT_QT信号与槽机制
开发语言·数据库·qt
辞旧 lekkk6 分钟前
【Qt】 系统相关:事件与定时器
开发语言·qt·学习·萌新
Wang's Blog8 分钟前
Java框架快速入门: Spring Bean核心配置与实例化详解
java·开发语言·spring
promising_xxx12 分钟前
深度学习个人开源知识库 深度筑基 | DeepBase
人工智能·python·深度学习·计算机视觉·ai·语言模型·nlp
三十岁老牛再出发21 分钟前
07.07.每日总结
c语言·windows·python
aaPIXa62229 分钟前
C++ TensorRT Edge-LLM 边缘推理框架:从原理到实战
开发语言·c++·edge
C137的本贾尼38 分钟前
MCP 完全指南:从零开始掌握模型上下文协议
人工智能·python
阿pin43 分钟前
Java随笔-GC收集器工作机制
java·开发语言·jvm·gc
2601_962440841 小时前
计算机毕业设计之jsp旅游网站管理系统
java·开发语言·算法·课程设计·旅游·推荐算法