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

相关推荐
小高不明13 分钟前
前缀和一维/二维-复习篇
开发语言·算法
龘龍龙17 分钟前
Python基础(八)
开发语言·python
幺零九零零1 小时前
Golang-Swagger
开发语言·后端·golang
vibag1 小时前
FastAPI框架
python·pycharm·fastapi
站大爷IP1 小时前
从零开始用Python生成码:自定义样式与Logo嵌入
python
陌路物是人非2 小时前
记一个 @Resource BUG
java·开发语言·bug
怎么就重名了2 小时前
记录Qt的UDP通信丢包问题
开发语言·qt·udp
superman超哥2 小时前
Rust 闭包的定义与捕获:所有权系统下的函数式编程
开发语言·后端·rust·函数式编程·rust闭包·闭包的定义与捕获
曹牧2 小时前
Java:Math.abs()‌
java·开发语言·算法
天才测试猿2 小时前
2026全新软件测试面试八股文【含答案+文档】
自动化测试·软件测试·python·功能测试·测试工具·面试·职场和发展