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

相关推荐
早日退休!!!几秒前
进程与线程的上下文加载_保存及内存映射
开发语言
jllllyuz1 分钟前
MATLAB实现蜻蜓优化算法
开发语言·算法·matlab
清水白石00814 分钟前
解构异步编程的两种哲学:从 asyncio 到 Trio,理解 Nursery 的魔力
运维·服务器·数据库·python
冰暮流星17 分钟前
javascript逻辑运算符
开发语言·javascript·ecmascript
flysh0517 分钟前
如何利用 C# 内置的 Action 和 Func 委托
开发语言·c#
山海青风18 分钟前
图像识别零基础实战入门 1 计算机如何“看”一张图片
图像处理·python
码农小韩39 分钟前
基于Linux的C++学习——动态数组容器vector
linux·c语言·开发语言·数据结构·c++·单片机·学习
木风小助理40 分钟前
`mapfile`命令详解:Bash中高效的文本至数组转换工具
开发语言·chrome·bash
彼岸花开了吗1 小时前
构建AI智能体:八十、SVD知识整理与降维:从数据混沌到语义秩序的智能转换
人工智能·python·llm
yyy(十一月限定版)1 小时前
初始matlab
开发语言·matlab