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

相关推荐
兔子小灰灰21 小时前
jetson安装pytorch
人工智能·pytorch·python
运维行者_21 小时前
OPM 与传统管理工具的区别,在网络修复与自动化运维方面的优势在哪里?
运维·服务器·开发语言·网络·自动化·php·ssl
广州灵眸科技有限公司21 小时前
瑞芯微(EASY EAI)RV1126B 音频输入
linux·开发语言·网络·音视频
Swizard21 小时前
拒绝“裸奔”上线:FastAPI + Pytest 自动化测试实战指南
python
吃喝不愁霸王餐APP开发者1 天前
基于Spring Cloud Gateway实现对外卖API请求的统一鉴权与流量染色
java·开发语言
心疼你的一切1 天前
三菱FX5U PLC与C#通信开发指南
开发语言·单片机·c#
Tim_101 天前
【C++入门】04、C++浮点型
开发语言·c++
Ven%1 天前
从单轮问答到连贯对话:RAG多轮对话技术详解
人工智能·python·深度学习·神经网络·算法
@淡 定1 天前
Java内存模型(JMM)详解
java·开发语言
谈笑也风生1 天前
经典算法题型之复数乘法(二)
开发语言·python·算法