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

相关推荐
学逆向的2 小时前
C 堆区内存管理
c语言·开发语言·网络安全
huoyueyi2 小时前
《融天AI-APP从0到1开发实录》
开发语言·lua
曲径海盗2 小时前
【Python 学习第 38 天】for 循环
python·学习笔记·编程入门
在世修行3 小时前
智学文枢:变式题生成引擎
python·ai·pyside·题目生成
OpenAnolis小助手4 小时前
PHP 两个严重漏洞曝光,龙蜥社区 24 小时完成 3 版本修复
开发语言·操作系统·php·龙蜥社区
On The Road :4 小时前
Java 多线程详解:从入门到线程安全
java·python·安全
阿尼卡~4 小时前
VS Code 配置 C 语言开发环境(Windows 10/11):从 GCC 安装到运行、断点调试,一篇搞定
c语言·开发语言·windows
岁月宁静5 小时前
如何设计支持 Skills 的 Agent?一套可扩展的四层架构
python·agent
岁月宁静5 小时前
CrewAI 快速上手:10 分钟搭建你的第一个 Agent 团队
python·agent
曲径海盗5 小时前
【Python 学习第 40 天】for 循环
python·学习笔记·编程入门