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 小时前
用 Python 和 OpenCV 提取书法作品中的每一个单字
python·opencv·计算机视觉
rayyy913 小时前
卡牌抽取游戏
开发语言·python
阿里嘎多学长13 小时前
2026-05-28 GitHub 热点项目精选
开发语言·程序员·github·代码托管
小白学大数据13 小时前
电商关键词挖掘:Java 爬虫抓取 1688 推荐搜索词
java·开发语言·爬虫·python
风兮雨露14 小时前
Python 3 从入门到精通教程 第一期
开发语言·python
A charmer14 小时前
零基础学OC:变量与基本数据类型(C++开发者速通版)[特殊字符]
开发语言·c++·objective-c
bjzhang7514 小时前
python开发环境安装及30个常用第三方库
开发语言·python
财经资讯数据_灵砚智能14 小时前
基于全球经济类多源新闻的NLP情感分析与数据可视化(日间)2026年5月28日
大数据·人工智能·python·信息可视化·自然语言处理·ai编程·灵砚智能
索西引擎14 小时前
【LangChain 1.0】环境搭建指南:从 conda 到 uv 的现代化 Python 工程实践
python·langchain·conda