python多线程 线程状态检测执行错误

问题:自定义超时检测装饰器 两种写法 超时功能都是正常的 ,然而一种方法在代码不超时的场景下 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()
    

回答不易 求求您采纳点赞哦 感激不尽

您遇到的问题是因为在第二种写法中,watchdog 函数使用了 thread.is_alive 属性判断线程是否还活着,但实际上 thread.is_alive 是一个方法,需要加上圆括号。

因此,可以在 watchdog 函数中更改代码:

if thread.is_alive():

改为:

if thread.is_alive():

这样就能正确判断线程是否还活着,避免在不超时的情况下打印超时语句。

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^