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

相关推荐
蚰蜒螟18 分钟前
从内核启动到 Java NIO:一次 socket accept 的源码串联之旅
java·python·nio
学逆向的33 分钟前
C 突破编译器限制
c语言·开发语言·网络安全
jimy11 小时前
C++ 虚函数表:基类和派生类共用一张 vtable 吗?
开发语言·c++
高洁011 小时前
AI赋能产业升级与中美未来经济赛道博弈
人工智能·python·深度学习·机器学习·transformer
爱吃提升1 小时前
Dev-C++ 5.11 C++断点调试完整教程
开发语言·c++
夜晚回家1 小时前
Python 原始字符串详解 | r 前缀到底让什么不再转义
开发语言·python
陈年老古董1 小时前
PyQt5 入门指南:环境搭建、PyCharm 外部工具配置与登录界面实战
开发语言·qt·pycharm
看浪的路人1 小时前
第7讲:大模型后端服务化——Go 实现高并发 LLM Proxy / Router / Fallback
开发语言·后端·golang
用户019027581611 小时前
如何用 Python 计算 EMV 简易波动指标?
python
第25小时记录1 小时前
[2026] Linux安装教程
运维·python