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

相关推荐
小趴蔡ha1 小时前
02 Anaconda、Python 与机器学习开发环境入门
python·机器学习·anaconda
2401_868534781 小时前
RTOS之RT-Thread & Linux:线程/进程管理与调度核心差异分析
c++·python
zzzll11111 小时前
Claude Code离线安装方案揭秘
开发语言·php
数字化转型分享点滴2 小时前
富士康、蓝思科技为何选择四化信息?MES制造执行系统的实践
python·科技
wling03012 小时前
vasp虚频计算-python脚本
开发语言·windows·python·vasp计算
魔镜前的帅比2 小时前
(开源项目)x-claw(总)
python·ai·rust·开源
郝学胜-神的一滴2 小时前
Qt 高级编程 040:按钮悬浮弹出滑块弹窗的完整攻略
开发语言·c++·qt·软件工程·用户界面
xrandzj3 小时前
Python面向对象编程入门:类、实例、初始化与封装实践
开发语言·python
DLYSB_4 小时前
API 网关流量洪峰与突发 CC 攻击:我用 Go 写了个“现场物理防御哨兵”,把故障响应压缩到秒级
开发语言·后端·golang·报警灯
matlabgoodboy6 小时前
计算机毕设代做|Java Python Matlab APP 全套开发设计
java·python·课程设计