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

相关推荐
一个帅气昵称啊10 小时前
.Net C# AI智能体开发-快速开始
开发语言·c#·.net
kyrie_sakura10 小时前
python学习笔记3 -- 流程控制语句结构
笔记·python·学习
冬夜戏雪10 小时前
agent的trace 和eval
开发语言·前端·javascript
程序员小八77710 小时前
Java 快速转 Go
java·python·golang
Sagittarius_A*10 小时前
Burst Lab | PHP 审计 13|反序列化(三):POP 链构造与 Gadget Chain 分析
开发语言·web安全·php·代码审计·反序列化
职场的momo10 小时前
11个后端与AI岗位同时开放:Java、网关、推理优化怎么匹配
java·开发语言·人工智能
蓝速科技11 小时前
蓝速科技丨新旧楼宇混杂场景下会议室预约门牌屏一体化改造方案
开发语言·科技·php
梦想的旅途211 小时前
Python实现企业微信文本消息发送
开发语言·python·企业微信
%4712 小时前
DAY41
pytorch·python
敲代码还房贷12 小时前
VMware17 + Ubuntu22.04 共享 完整步骤
linux·python·ubuntu