Python线程超时控制

2021-03-07 23:30

阅读:596

标签:控制   from   exce   http   read   else   target   fun   rgs   

 

# #!/usr/bin/env python
# # coding: utf-8
# # https://www.cnblogs.com/scolia/p/6132950.html
import threading
import time
import signal

def set_timeout(num):
    def wrap(func):
        def handle(signum, frame):
            signal.alarm(0)
            raise RuntimeError

        def todo(self, *args, **kwargs):
            try:
                print(f"in todo self:{self}")
                signal.signal(signal.SIGALRM, handle)
                signal.alarm(num)  # 设置定时器
                print("设置定时器完成")
                r = func(self, *args, **kwargs)
                # signal.alarm(0)  # signal.alarm(0)  # 关闭定时器, 这里不能阻塞
                # print("关闭定时器")
                # return r
            except RuntimeError:
                print(f"signal超时,准备停止线程")
                self.coo.tmp_thread.stop() # 是否真的调用了stop/
                print(f"signal超时,停止线程 done")
                raise Exception
        return todo
    return wrap


class Job(threading.Thread):

    def __init__(self, *args, **kwargs):
        super(Job, self).__init__(*args, **kwargs)
        self.__running = threading.Event()      # 用于停止线程的标识
        self.__running.set()      # 将running设置为True
        # self.running = True

    def run(self):
        while True:
            if self.__running.isSet():
                print("子线程运行中... ", time.time())
                time.sleep(1)
            else:
                print("子线程退出....")
                print("子线程退出....")
                return

            print("in while True")


    def stop(self):
        print("调用线程stop")
        time.sleep(1)
        self.__running.clear()        # 设置为False
        # self.running = False
        print("调用线程stop done")
        time.sleep(1)


# 线程的停止:注意如果是阻塞的无法完成stop
class Coo():

    def __init__(self):
        self.tmp_thread = None

    def execute(self):
        t = Job()
        t.setDaemon(True)
        t.start()
        self.tmp_thread = t
        t.join()
        # time.sleep(8)
        # t.stop()

class CustErr(Exception):
    pass

class Foo():
    def __init__(self):
        self.coo = Coo()

    # def handle(self, signum, frame):
    #     signal.alarm(0)
    #     # self.coo.tmp_thread.stop()
    #     raise CustErr

    @set_timeout(num=3)
    def foo_main(self):
        self.coo.execute()
        # try:
        #     signal.signal(signal.SIGALRM, self.handle)
        #     signal.alarm(3)
        #     print(f"in foo main self:{self}")
        #     self.coo.execute()
        # except CustErr:
        #     print("catch Cust Err...")
        #     self.coo.tmp_thread.stop()

def main():
    a = Foo()
    a.foo_main()

from multiprocessing import Process
p1=Process(target=main,args=())
p1.start()

print("主线程结束退出")

 

Python线程超时控制

标签:控制   from   exce   http   read   else   target   fun   rgs   

原文地址:https://www.cnblogs.com/yum777/p/14250140.html


评论


亲,登录后才可以留言!