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

相关推荐
小白学大数据9 分钟前
现代Python爬虫开发范式:基于Asyncio的高可用架构实战
开发语言·爬虫·python·架构
渔舟小调19 分钟前
P19 | 前端加密通信层 pikachuNetwork.js 完整实现
开发语言·前端·javascript
不爱吃炸鸡柳21 分钟前
数据结构精讲:树 → 二叉树 → 堆 从入门到实战
开发语言·数据结构
网络安全许木21 分钟前
自学渗透测试第21天(基础命令复盘与DVWA熟悉)
开发语言·网络安全·渗透测试·php
t***54426 分钟前
如何在Dev-C++中使用Clang编译器
开发语言·c++
qq_6543669829 分钟前
CSS如何处理@import样式表的嵌套加载_评估递归对加载的影响
jvm·数据库·python
weixin_3812881830 分钟前
苹果微软双修党福音:Navicat如何跨系统平滑迁移配置
jvm·数据库·python
xcbrand31 分钟前
政府事业机构品牌策划公司找哪家
大数据·人工智能·python
码界筑梦坊35 分钟前
93-基于Python的中药药材数据可视化分析系统
开发语言·python·信息可视化
阿荻在肝了38 分钟前
Agent学习六:LangGraph学习-持久化与记忆一
python·学习·agent