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

相关推荐
2501_9475758013 小时前
计算机毕业设计之jsp开山车行二手车交易系统
java·开发语言·hadoop·python·信息可视化·django·课程设计
骑士雄师13 小时前
java面试题 4:鉴权
java·开发语言
Byron__14 小时前
AI学习_06_短期记忆与长期记忆
人工智能·python·学习
时间的拾荒人14 小时前
C语言字符函数与字符串函数完全指南
c语言·开发语言
2501_9481069115 小时前
计算机毕业设计之基于jsp教科研信息共享系统
java·开发语言·信息可视化·spark·课程设计
取经蜗牛15 小时前
Python 第一阶段完全指南:从零到第一个实用工具
开发语言·python
创世宇图15 小时前
【Python工程化实战】OpenTelemetry 在 Python 中的全链路追踪落地:从埋点到可视化的完整实战指南
python·分布式链路追踪·性能监控·opentelemetry·微服务可观测性
dog25015 小时前
从重尾到截断流量模型的演进
开发语言·php
qq_4017004116 小时前
Qt QSS 完全入门写出漂亮界面以及解决样式不生效问题
开发语言·qt
许彰午16 小时前
72_Python爬虫基础BeautifulSoup
爬虫·python·beautifulsoup