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

相关推荐
传奇开心果编程几秒前
【Rust入门练中学】 第1课:从零开始
开发语言·学习·rust
K 旺仔小馒头1 分钟前
【项目】商城系统用户端测试报告
自动化测试·python·功能测试
东莞市云毅网络有限公司13 分钟前
用 SQLite FTS5 给企业文档建本地全文索引:中文分词与权重调优
python·数据清洗·rag·企业知识库·文档解析
钱栈up14 分钟前
health从200变000:一次差点引发双端口冲突的后端巡检复盘
python
正经教主15 分钟前
【FDE系列】阶段2:Day 22:变量、数据类型、条件判断 — Python 的“记忆“和“判断“
人工智能·python·fde
Brilliantwxx39 分钟前
【STM32】 SPI阻塞式通信与HAL源码(串口读ID实战)
开发语言·stm32·单片机·嵌入式硬件·ecmascript
打工仔折腾 AI44 分钟前
Pascal Editor 本地部署实战:Bun 启动 WebGPU 3D 编辑器并解决公网访问报错
人工智能·后端·python·性能优化
m0_547486661 小时前
《Python从入门到数据分析应用》全套PPT课件2026
python·数据分析
All for pursuit.1 小时前
FastAPI+Ollama 部署本地AI大模型对话助手
python·github·aigc·ollama
吠品1 小时前
Nginx负载均衡配置与线上故障排查的一些经验
java·开发语言·数据库