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

相关推荐
起予者汝也6 分钟前
Python 数据结构
开发语言·数据结构·python
LadenKiller8 分钟前
2026年量化工具增量,放回回测模拟实盘阶段判断
人工智能·python
石一峰69912 分钟前
驱动:私有数据为什么要在三个地方各挂一遍?
数据库·python·算法
2601_9563198815 分钟前
最新量化软件怎么选,先按能力短板匹配工具类型
人工智能·python
Tbisnic29 分钟前
26.AI大模型:RNN、LSTM、GRU
人工智能·python·rnn·gru·大模型·llm·lstm
七夜zippoe1 小时前
OpenClaw 实战:智能文档助手——从问答到生成的完整方案
人工智能·python·机器学习·openclaw·智能文档
卡提西亚2 小时前
leetcode-179. 最大数
python·算法
ECT-OS-JiuHuaShan2 小时前
严格证明:还原论是ASCII,整体论是UTF-8的历史意义和价值
开发语言·人工智能·算法·量子计算
AC赳赳老秦2 小时前
时间开销自动统计:OpenClaw 记录工作任务时长、分析时间分配、给出优化建议
java·大数据·开发语言·python·自动化·deepseek·openclaw
清水白石0082 小时前
Python 类定义阶段自动注册子类:从 `__init_subclass__` 到插件系统实战
linux·前端·python