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

相关推荐
wefly20171 小时前
纯前端架构深度解析:jsontop.cn,JSON 格式化与全栈开发效率平台
java·前端·python·架构·正则表达式·json·php
551只玄猫1 小时前
【数学建模 matlab 实验报告1】
开发语言·数学建模·matlab·课程设计·实验报告
胡耀超1 小时前
Token的八副面孔:为什么“词元“不需要更好的翻译,而需要更多的读者
大数据·人工智能·python·agent·token·代币·词元
三道渊2 小时前
C语言:文件I/O
c语言·开发语言·数据结构·c++
hnlgzb2 小时前
安卓app kotlin语法,Hilt是什么东西?
android·开发语言·kotlin
没用的阿_吉2 小时前
windows10 Qt5.15.14 msvc2019 编译部署
开发语言·qt
聊聊MES那点事2 小时前
JavaScript图表控件AG Charts使用教程:使用AG Charts React实时更新柱状图
开发语言·javascript·react.js·图表控件
ywf12152 小时前
Go基础之环境搭建
开发语言·后端·golang
biubiubiu07062 小时前
Python 环境安装与 Linux 控制入门
linux·开发语言·python
第一程序员2 小时前
Python与前端集成:构建全栈应用
python·github