python强制停止线程学习

参考:

Python进阶之路 - Timeout | 超时中断 - 知乎 (zhihu.com)

写的很棒。

这里只记录我摘取的封装的一个class:

python 复制代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import ctypes
import threading


class ThreadKillOver(RuntimeError):
    """
    线程杀死后的反馈
    """
    def __init__(self):
        RuntimeError.__init__(self, "ThreadKillOver")

class ThreadKiller(threading.Thread):
    """separate thread to kill TerminableThread"""

    def __init__(self, target_thread, exception_cls, repeat_sec=2.0):
        threading.Thread.__init__(self)
        self.target_thread = target_thread
        self.exception_cls = exception_cls
        self.repeat_sec = repeat_sec
        self.daemon = True

    def run(self):
        """loop raising exception incase it's caught hopefully this breaks us far out"""
        while self.target_thread.is_alive():
            #ctypes.pythonapi.PyThreadState_SetAsyncExc是Python的ctypes库中的一个函数,
            # 用于设置Python线程的异步异常。这个函数的第一个参数是一个C语言中的线程状态对象,
            # 第二个参数是要抛出的异常。这个函数允许你在Python的C API层面控制线程的异常处理,
            # 通常情况下,你不需要直接使用这个函数,而是让Python的异常处理机制自动处理。
            ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(self.target_thread.ident),
                                                       ctypes.py_object(self.exception_cls))
            self.target_thread.join(self.repeat_sec)


class TerminableThread(threading.Thread):
    """a thread that can be stopped by forcing an exception in the execution context"""

    def terminate(self, exception_cls=ThreadKillOver, repeat_sec=1.0):
        """
        一个是exception_cls,这个的含义是,线程结束时会raise哪一种异常;
        另一个是repeat_sec,这个的含义是,杀手每隔多长时间去确认一次线程有没有死亡。
        如果repeat_sec为1,则线程杀手会每秒检查一次,如果线程还没死,就再杀一次,知道确认死亡为止。
        """
        if self.is_alive() is False:
            return True
        killer = ThreadKiller(self, exception_cls, repeat_sec=repeat_sec)
        killer.start()
相关推荐
小陈工6 分钟前
第8篇:Flask轻量级框架与扩展生态深度解析(下)
后端·python·面试
woshihuanglaoshi10 分钟前
参数验证_Flutter在鸿蒙平台确保路由参数类型安全
学习·flutter·华为·harmonyos·鸿蒙·鸿蒙系统
小刘学技术15 分钟前
AI人工智能中的类别不平衡问题:成因、影响与解决方案
开发语言·人工智能·python·机器学习
小大宇24 分钟前
mongoDB dump技巧
数据库·mongodb
郝同学今天有进步吗24 分钟前
构建 LangGraph Code Review Agent(二):建立仓库路径安全边界
python·ai·code review
huijingjituan26 分钟前
三方聊天软件工具定制开发|打造企业级智能通讯平台
数据库·安全·阿里云·实时互动·腾讯云
zyplayer-doc29 分钟前
研发接口文档怎么长期维护:zyplayer-doc把API、Markdown和变更记录放进同一个知识库
大数据·数据库·人工智能·笔记·pdf·ocr
NineData30 分钟前
Oracle 卡住时先看阻塞源,ChatDBA 会先把锁链路理出来
数据库·oracle·ninedata·锁故障·锁等待·chatdba·锁阻塞
雨师@34 分钟前
python通过rust编写组件扩展自己的能力
python·rust
一本杂志42 分钟前
某航 cookies:ssxmod_itna、ssxmod_itna2参数逆向分析思路学习
学习