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

相关推荐
Emily1568535987016 分钟前
Emerson 1C31129G03 Analog Input Module
java·开发语言·前端·plc·emerson·1c31129g03·input module
就叫_这个吧5 小时前
Java递归方法实现面包屑导航
java·开发语言
fīɡЙtīиɡ ℡5 小时前
AI 应用系统设计
java·开发语言·人工智能
聪明蛋子哟6 小时前
Stagehand v3多语言SDK:Python/Go/Rust/Java下的浏览器自动化统一方案
python·golang·rust
今天AI了吗7 小时前
Python 基础语法(一):常量、变量、输入输出与运算符
开发语言·数据库·人工智能·python·sql·深度学习·机器学习
卷无止境7 小时前
Windows 上丝滑开发 Python,并稳定构建 Docker 镜像
后端·python·docker
TELL5217 小时前
selenium webdriver 第二次初始化的异常
开发语言·python
Csvn8 小时前
🐍 Day 4: Python 控制流 — 条件、循环与推导式的艺术
后端·python
动词ing8 小时前
【C语言】自定义函数+指针入门
c语言·开发语言·算法
重生之后端学习8 小时前
283. 移动零[简单]✅
开发语言·数据结构·算法·leetcode·职场和发展