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

相关推荐
W_a_i_T1 分钟前
【Coding日记】菜鸟编程C语言100例——第三题⚠️
c语言·开发语言·经验分享·算法·菜鸟编程
Blossom.1183 分钟前
把大模型塞进蓝牙耳机:1.46MB 的 Whisper-Lite 落地全记录
人工智能·笔记·python·深度学习·神经网络·chatgpt·whisper
weixin_452159553 分钟前
多协议网络库设计
开发语言·c++·算法
十五年专注C++开发4 分钟前
浅谈C++插件机制的设计要点以及实现方案
开发语言·c++·系统架构·插件机制
Hello World . .4 分钟前
C语言printf: VT100 终端控制码
c语言·开发语言·jvm
爱装代码的小瓶子5 分钟前
【C++与Linux基础】文件篇 -语言特性上的文件操作
linux·开发语言·c++
C+-C资深大佬7 分钟前
C++优化
开发语言·c++
Echo_NGC223712 分钟前
【联邦学习入门指南】 Part 2:核心挑战与安全机制
人工智能·python·深度学习·安全·机器学习·联邦学习
2301_7886624013 分钟前
C++与微服务架构
开发语言·c++·算法
风好衣轻18 分钟前
[AI] max_num_seqs 参数详解
人工智能·python·深度学习