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

相关推荐
仟濹28 分钟前
【Java基础】多态 | 打卡day2
java·开发语言
孞㐑¥28 分钟前
算法——BFS
开发语言·c++·经验分享·笔记·算法
Re.不晚29 分钟前
JAVA进阶之路——无奖问答挑战2
java·开发语言
八零后琐话32 分钟前
干货:程序员必备性能分析工具——Arthas火焰图
开发语言·python
3GPP仿真实验室34 分钟前
【MATLAB源码】CORDIC-QR :基于Cordic硬件级矩阵QR分解
开发语言·matlab·矩阵
知南x1 小时前
【Ascend C系列课程(高级)】(1) 算子调试+调优
c语言·开发语言
忆~遂愿1 小时前
GE 引擎与算子版本控制:确保前向兼容性与图重写策略的稳定性
大数据·开发语言·docker
Ro Jace1 小时前
计算机专业基础教材
java·开发语言
代码游侠2 小时前
学习笔记——设备树基础
linux·运维·开发语言·单片机·算法