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

相关推荐
2601_962780915 分钟前
需求预测校招能力栈|2026 届 JD 梳理、日常任务、面试题与备考方案
python·数据挖掘·数据分析
HEJOO99 分钟前
指针与结构体:C 语言进阶核心详解
c语言·开发语言·网络
乌暮12 分钟前
JVM 原理与实践:从运行时数据区到线上故障排查
java·开发语言·jvm·后端·学习·面试
miofly12 分钟前
GitHub 今日推荐|lipflow:无麦克风唇读文字输入工具
python·开源·github
架构师那点事儿17 分钟前
将 HuggingFace 自己的英译中模型迁移到 ONNX
人工智能·python·深度学习
维克兜率天32 分钟前
【维克】配对交易的季节性:哪些品种适合长拿?
android·开发语言·笔记·python·算法·kotlin·量化
276695829239 分钟前
国航京东验证码/sm2加密请求头算法采集分析
python·阿里云·国航·机票采集·国航京东验证码·京东验证码·京东点选验证码
沫璃染墨1 小时前
《Qt从零入门系列(十二):Qt文件操作详解——从QFile读写到QFileInfo与记事本实战》
开发语言·网络·c++·qt·交互·信号处理·文件
青少儿编程课堂1 小时前
树上启发式合并详解:子树颜色众数统计与复杂度拆解
c++·python·算法·bfs·信息学竞赛