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

相关推荐
沐知全栈开发1 小时前
HTML DOM 修改
开发语言
2501_941236212 小时前
C++与Node.js集成
开发语言·c++·算法
2501_941111342 小时前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python
晨非辰2 小时前
【数据结构初阶系列】归并排序全透视:从算法原理全分析到源码实战应用
运维·c语言·数据结构·c++·人工智能·python·深度学习
A尘埃2 小时前
Python后端框架:FastAPI+Django+Flask
python·django·flask·fastapi
菠菠萝宝3 小时前
【Java手搓RAGFlow】-3- 用户认证与权限管理
java·开发语言·人工智能·llm·openai·qwen·rag
蒋星熠4 小时前
实证分析:数据驱动决策的技术实践指南
大数据·python·数据挖掘·数据分析·需求分析
独行soc5 小时前
2025年渗透测试面试题总结-250(题目+回答)
网络·驱动开发·python·安全·web安全·渗透测试·安全狮
csdn_wuwt5 小时前
前后端中Dto是什么意思?
开发语言·网络·后端·安全·前端框架·开发
print(未来)5 小时前
C++ 与 C# 的性能比较:选择合适的语言进行高效开发
java·开发语言