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

相关推荐
橘子编程17 小时前
仓颉语言变量与表达式解析
java·linux·服务器·开发语言·数据库·python·mysql
LXS_35717 小时前
Day 15 C++之文件操作
开发语言·c++·学习方法·改行学it
无限进步_17 小时前
基于单向链表的C语言通讯录实现分析
c语言·开发语言·数据结构·c++·算法·链表·visual studio
老鱼说AI17 小时前
算法初级教学第四步:栈与队列
网络·数据结构·python·算法·链表
忘记92618 小时前
什么是stream流
开发语言
wxl78122718 小时前
从图片PDF到结构化文本:基于Python+Dify的批量OCR自动化解决方案
python·pdf·ocr
上78将18 小时前
JVM回收垃圾机制
java·开发语言·jvm
张人玉18 小时前
C#Https协议相关知识点
开发语言·https·c#
刘一说18 小时前
JDK 25新纪元:技术革新与老项目迁移的冷思考
java·开发语言
Byron Loong18 小时前
【C#】VS调试——带参调试
开发语言·c#