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

相关推荐
strive-debug1 天前
cpp基础入门~~c语言的补足
开发语言·c++
DeepFlow 零侵扰全栈可观测1 天前
民生银行云原生业务的 eBPF 可观测性建设实践
运维·开发语言·分布式·云原生·金融·php
每天回答3个问题1 天前
Lua 函数教程
开发语言·ue5·ue4·lua
后端小张1 天前
【JAVA 进阶】Spring Boot 中 AOP 切面编程全解析:从基础到实战进阶
java·开发语言·人工智能·spring boot·后端·spring·spring cloud
天天进步20151 天前
Python全栈项目--基于Django的项目管理系统
开发语言·python·django
h_jQuery1 天前
vue项目中使用canvas实现手写文字(批注)功能
开发语言·前端·javascript
小北方城市网1 天前
第 3 课:微服务架构设计与服务治理|从分布式到微服务的进阶实战
开发语言·人工智能·分布式·python·微服务·架构·geo
superman超哥1 天前
Rust Cell与RefCell的使用场景与区别:内部可变性的精确选择
开发语言·后端·rust·refcell·rust cell·内部可变性·精确选择
搞全栈小苏1 天前
【Python 爬虫实战】一键批量下载 Python 官网 FTP 所有版本全部文件(多线程 + 断点续传 + 禁用系统代理 完整版)
开发语言·爬虫·python