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

相关推荐
杰瑞哥哥5 分钟前
【时间序列与深度学习】(一)经济计量基础ARIMA模型
python·时间序列·金融工程
低调小一7 分钟前
Kotlin 2025–2026 客户端开发路线:语言升级 × 跨端落地 × AI Agent 入门
开发语言·人工智能·kotlin
网安CILLE16 分钟前
Wireshark 抓包实战演示
linux·网络·python·测试工具·web安全·网络安全·wireshark
研☆香17 分钟前
JS中的三种显示弹窗
开发语言·前端·javascript
王夏奇23 分钟前
python中的基础知识点-1
开发语言·windows·python
叫我辉哥e124 分钟前
新手进阶Python:办公看板集成多数据源+ECharts高级可视化
开发语言·python·echarts
猛扇赵四那边好嘴.24 分钟前
Flutter 框架跨平台鸿蒙开发 - 问答社区应用开发教程
开发语言·javascript·flutter·华为·harmonyos
C_心欲无痕26 分钟前
Next.js 路由系统对比:Pages Router vs App Router
开发语言·前端·javascript
LawrenceLan29 分钟前
Flutter 零基础入门(二十二):Text 文本组件与样式系统
开发语言·前端·flutter·dart
程序员敲代码吗29 分钟前
如何从Python初学者进阶为专家?
jvm·数据库·python