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

相关推荐
干啥啥不行,秃头第一名7 分钟前
Python深度学习入门:TensorFlow 2.0/Keras实战
jvm·数据库·python
工程师老罗12 分钟前
LVGL文本显示问题,编码问题
java·开发语言
痴心阿文12 分钟前
npx create-next-app@latest从Vue迁移的最佳实践
开发语言·前端·javascript
宵时待雨13 分钟前
C++笔记归纳15:红黑树
开发语言·数据结构·c++·笔记
黑眼圈子14 分钟前
牛客刷题记录5
java·开发语言·学习·算法
枫叶丹416 分钟前
【HarmonyOS 6.0】OAID服务正式支持TV设备
开发语言·华为·harmonyos
NGC_661120 分钟前
ConcurrentHashMap介绍
java·开发语言
JY.yuyu22 分钟前
Java Web上架流程(Nginx反向代理+负载均衡 ,Apache配置,Maven安装打包,Tomcat配置)
java·开发语言·前端
sin°θ_陈22 分钟前
前馈式3D Gaussian Splatting 研究地图(路线一):像素对齐高斯的起点——pixelSplat 与 latentSplat 在解决什么
python·深度学习·3d·aigc·webgl·3dgs·空间智能