美文网首页
python线程超时自动关闭

python线程超时自动关闭

作者: 王文强Python | 来源:发表于2022-02-19 16:20 被阅读0次

    上一段简写代码

    from threading import Thread
    
    def timeout(seconds = 5,hint=''):
        def handler():
            raise Exception(f'{hint}执行超时!timeout = {seconds}s')
        def wrap(func):
            def outter(*args,**kwargs):
                signal.signal(signal.SIGALRM,handler)
                signal.alarm(seconds)
                res = func(*args,**kwargs)
                signal.alarm(0)
                return res
            return outter
        return wrap
    
    def fun(a):
        print(a)
    
    @timeout(10,'请求资源')
    def threadfunc():
        t = Thread(fun,args=(1,))
        t.start()
        t.join()
    

    相关文章地址:
    https://www.cnblogs.com/mymelody/p/9299155.html
    https://blog.csdn.net/jhonguy/article/details/7716257

    相关文章

      网友评论

          本文标题:python线程超时自动关闭

          本文链接:https://www.haomeiwen.com/subject/xdjplrtx.html