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

相关推荐
csdn_aspnet5 分钟前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
fantasy_arch28 分钟前
pytorch人脸匹配模型
人工智能·pytorch·python
熊猫_豆豆28 分钟前
广义相对论水星近日点进动完整详细数学推导
python·天体·广义相对论
LuminousCPP31 分钟前
数据结构 - 线性表第四篇:C 语言通讯录优化升级全记录(踩坑 + 思考)
c语言·开发语言·数据结构·经验分享·笔记·学习
web3.088899941 分钟前
1688 图搜接口(item_search_img / 拍立淘) 接入方法
开发语言·python
AI算法沐枫1 小时前
深度学习python代码处理科研测序数据
数据结构·人工智能·python·深度学习·决策树·机器学习·线性回归
один but you1 小时前
从可变参数到 emplace:现代 C++ 性能优化的核心组合
java·开发语言
X1A0RAN2 小时前
解决Pycharm中部分文件或文件夹被隐藏不展示问题
ide·python·pycharm
MomentYY2 小时前
第 3 篇:让 Agent 学会分工,LangGraph 构建多 Agent系统
人工智能·python·agent
MY_TEUCK2 小时前
【Java 后端 | Nacos 注册中心】微服务治理原理、选型与注册发现实战
java·开发语言·微服务