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

相关推荐
WangYaolove131416 分钟前
Python基于大数据的电影市场预测分析(源码+文档)
python·django·毕业设计·源码
知乎的哥廷根数学学派27 分钟前
基于自适应多尺度小波核编码与注意力增强的脉冲神经网络机械故障诊断(Pytorch)
人工智能·pytorch·python·深度学习·神经网络·机器学习
yeziyfx35 分钟前
kotlin中 ?:的用法
android·开发语言·kotlin
charlie1145141911 小时前
嵌入式的现代C++教程——constexpr与设计技巧
开发语言·c++·笔记·单片机·学习·算法·嵌入式
古城小栈1 小时前
Rust 网络请求库:reqwest
开发语言·网络·rust
hqwest1 小时前
码上通QT实战12--监控页面04-绘制6个灯珠及开关
开发语言·qt·qpainter·qt事件·stackedwidget
i橡皮擦1 小时前
TheIsle恐龙岛读取游戏基址做插件(C#语言)
开发语言·游戏·c#·恐龙岛·theisle
cnxy1882 小时前
Python爬虫进阶:反爬虫策略与Selenium自动化完整指南
爬虫·python·selenium
bing.shao2 小时前
golang 做AI任务执行
开发语言·人工智能·golang
用户8356290780512 小时前
Python 实现 Excel 条件格式自动化
后端·python