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 小时前
LangChain 深入
人工智能·python·langchain
网安-轩逸4 小时前
回归测试原则:确保软件质量的基石
自动化测试·软件测试·python
Mr_Xuhhh4 小时前
YAML相关
开发语言·python
咖啡の猫4 小时前
Python中的变量与数据类型
开发语言·python
前端达人4 小时前
你的App消息推送为什么石沉大海?看Service Worker源码我终于懂了
java·开发语言
汤姆yu4 小时前
基于springboot的电子政务服务管理系统
开发语言·python
全栈师5 小时前
C#中控制权限的逻辑写法
开发语言·c#
S***q1925 小时前
Rust在系统工具中的内存安全给代码上了三道保险锁。但正是这种“编译期的严苛”,换来了运行时的安心。比如这段代码:
开发语言·后端·rust
执笔论英雄5 小时前
【RL】python协程
java·网络·人工智能·python·设计模式
打点计时器5 小时前
matlab 解决wfdb工具使用本地数据集报错
开发语言·matlab