问题:自定义超时检测装饰器 两种写法 超时功能都是正常的 ,然而一种方法在代码不超时的场景下 thread.is_ailve正常应该是不成立的 但是成立了 更改了很多次没找到原因求解答
demo1
import time
import threading
def watchdog(timeout):
time.sleep(timeout)
print('watchdog执行完毕')
return
def watchdog_decorator(timeout):
def decorator(func):
def wrapper(*args,**kwargs):
watchdog_thread=threading.Thread(target=watchdog,args=(timeout,))
watchdog_thread.start()
thread=threading.Thread(target=func,args=args,kwargs=kwargs)
thread.start()
#todo:当watcgdog_thread和thread线程都被创建之后 两个子线程 是同步执行的
watchdog_thread.join()#阻塞主线程 只有watchdog_thread子线程执行完之后才会执行下面的代码,使用join方法可以保证 主线程 等待子线程执行完毕后才继续执行 ,使用该方法能够保证子线程的执行完整性
if thread.is_alive():#如果wathcdog_thread线程执行完毕 thread线程还在执行的话 就证明已经超时
# print(thread.is_alive())
print(f"{thread.name} timeout")
# print(threading.current_thread())
# thread.stop=True# 如果 thread没有执行完的话停止 thread线程
else:
# print(thread.is_alive())
print("Main thread finished")
return wrapper
return decorator
@watchdog_decorator(3)#代码为超时示例
def test():
print('test函数开始执行')
time.sleep(2)
print('test函数执行结束')
@watchdog_decorator(1)#代码超时示例
def test2():
print('test2函数开始执行')
time.sleep(2)
print('test2函数执行结束')
if __name__ == '__main__':
# test()
test2()
demo2 不超时的情况下会打印超时语句
import threading
import time
def watchdog(thread,timeout) -> None:
'''
:param thread:
:param timeout:
:return: None
'''
time.sleep(timeout)
print('时间等待执行完毕')
if thread.is_alive:
print(f'{thread.name} timeout')
else:
return
def watchdog_decorator(timeout):
def decorator(func):
def wrapper(*args,**kwargs):
thread=threading.Thread(target=func,args=args,kwargs=kwargs)
thread.start()
# thread.run()
watchdog_thread=threading.Thread(target=watchdog,args=(thread,timeout))
watchdog_thread.start()
thread.join()
print("Main thread finished")
return wrapper
return decorator
@watchdog_decorator(3)
def test():
print('test函数开始执行')
time.sleep(1)
print('test函数执行结束')
if __name__ == '__main__':
test()