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

相关推荐
过客猫20221 分钟前
使用 deepseek实现 go语言,读取文本文件的功能,要求支持 ascii,utf-8 等多种格式自适应
开发语言·后端·golang
程序媛-徐师姐12 分钟前
基于 Python Django 的校园互助平台(附源码,文档)
开发语言·python·django·校园互助·校园互助平台
进击的_鹏30 分钟前
【C++】list 链表的使用+模拟实现
开发语言·c++·链表
大数据追光猿35 分钟前
【深度学习】Pytorch项目实战-基于协同过滤实现物品推荐系统
人工智能·pytorch·python·深度学习·ai编程·推荐算法
m0_7383556938 分钟前
java泛型
java·开发语言
师范大学生44 分钟前
基于CNN的FashionMNIST数据集识别2——模型训练
python·深度学习·cnn
web137656076431 小时前
纯 Python、Django、FastAPI、Flask、Pyramid、Jupyter、dbt 解析和差异分析
python·django·fastapi
大模型铲屎官1 小时前
哈希表入门到精通:从原理到 Python 实现全解析
开发语言·数据结构·python·算法·哈希算法·哈希表
L_09071 小时前
【C】队列与栈的相互转换
c语言·开发语言·数据结构
qq4054251971 小时前
基于python的旅客游记和轨迹分析可视化系统设计(新)
开发语言·python