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

相关推荐
山海青风15 小时前
藏文TTS介绍:6 MMS 项目的多语言 TTS
人工智能·python·神经网络·音视频
掘金詹姆斯15 小时前
1、为什么说精通 Python 就等于握住了 AI 时代的全栈通行证?
python
用户83562907805115 小时前
Python 操作 Excel:从基础公式到动态函数生成
后端·python
武当王丶也15 小时前
从零构建基于 RAG 的 AI 对话系统:Ollama + Python + 知识库实战
人工智能·python
想学后端的前端工程师16 小时前
【Java设计模式实战应用指南:23种设计模式详解】
java·开发语言·设计模式
小白勇闯网安圈16 小时前
Java的集合
java·开发语言
38242782716 小时前
python:正则表达式
前端·python·正则表达式
渣渣盟16 小时前
网络命令大全:轻松解决网络故障
开发语言·php
Mr Tang16 小时前
Docker日志查看和应用日志查看命令大全
java·开发语言
invicinble16 小时前
java处理数据合集
java·开发语言