python中函数超时退出

知道为啥threading仅有start而没有end不?

     线程一般用在网络连接、释放系统资源、dump流文件,这些都跟IO相关了,你突然关闭线程那这些没有合理地关闭怎么办会造成一定的影响

这里一种方案:

inspect模块用于收集python对象的信息,可以获取类或函数的参数的信息,源码,解析堆栈,对对象进行类型检查等等

inspect --- 检查对象 — Python 3.10.4 文档

ctypes是 Python 的外部函数库。它提供了与 C 兼容的数据类型,并允许调用 DLL 或共享库中的函数。可使用该模块以纯 Python 形式对这些库进行封装

ctypes --- Python 的外部函数库 — Python 3.10.4 文档


ctypes.c_long :代表 C signed long 数据类型。 该构造器接受一个可选的整数初始化器;不会执行溢出检查

ctypes.pythonapi:一个 PyDLL 的实例,它将 Python C API 函数作为属性公开。 请注意所有这些函数都应返回 C int,当然这也不是绝对的,因此你必须分配正确的 restype 属性以使用这些函数

ctypes.py_object:代表 C PyObject* 数据类型。 不带参数地调用此构造器将创建一个 NULL PyObject* 指针

import time
import sys
from threading import Thread
import inspect
import ctypes


def _async_raise(tid, exctype):
    tid = ctypes.c_long(tid)
    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:
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        raise SyntaxError("PyThreadState_SetAsyncExc failed")


def stop_thread(thread):
    _async_raise(thread.ident, SystemExit)


def time_limited(timelimit):
    def wrapper(func):
        def __wrapper(*args, **kwargs):
            class TimeLimited(Thread):
                def __init__(self):
                    Thread.__init__(self)

                def run(self):
                    print("设置超时时间为:%d 秒" % timelimit)
                    func(*args, **kwargs)

            t = TimeLimited()
            t.start()
            t.join(timeout=timelimit)
            if t.is_alive():
                print("程序运行:" + str(timelimit) + "秒超时报错退出")
            stop_thread(t)

        return __wrapper

    return wrapper


@time_limited(5)
def test():
    print("多线程开始测试......")
    time.sleep(10)
    print("多线程测试结束......")


test()

 

多线程程序确实别杀掉了,程序直接退出

 

posted @ 2022-04-26 14:58  醉城、  阅读(484)  评论(0编辑  收藏  举报