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()
相关推荐
Leon-Ning Liu2 分钟前
Oracle Data Guard Broker RedoRoutes 属性配置文档
数据库·oracle
拼好饭和她皆失10 分钟前
C#学习入门
开发语言·学习·c#
Sunhen_Qiletian13 分钟前
《Python开发之语言基础》第一集:python的语法元素
开发语言·python
速易达网络13 分钟前
tensorflow+yolo图片训练和图片识别系统
人工智能·python·tensorflow
LFly_ice32 分钟前
学习React-22-Zustand
前端·学习·react.js
程序员小远1 小时前
如何搭建Appium环境?
自动化测试·软件测试·python·测试工具·职场和发展·appium·测试用例
JIngJaneIL1 小时前
远程在线诊疗|在线诊疗|基于java和小程序的在线诊疗系统小程序设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·小程序·毕设·在线诊疗小程序
烟袅1 小时前
使用 OpenAI SDK 调用 Tools 实现外部工具集成
python·openai·agent
青瓷程序设计1 小时前
果蔬识别系统【最新版】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积神经网络算法
人工智能·python·深度学习
川石课堂软件测试1 小时前
自动化过程中验证码的解决思路
数据库·python·功能测试·测试工具·单元测试·tomcat·自动化