15

我注意到以下代码中的以下行为(使用 threading.Timer 类):

import threading

def ontimer():
    print threading.current_thread()

def main():
    timer = threading.Timer(2, ontimer)
    timer.start()
    print threading.current_thread()
    timer.cancel()
    if timer.isAlive():
        print "Timer is still alive"
    if timer.finished:
        print "Timer is finished"


 if __name__ == "__main__":
main()

代码的输出是:

<_MainThread(MainThread, started 5836)>
Timer is still alive
Timer is finished

正如我们从输出中注意到的那样,计时器对象仍然处于活动状态并且同时完成。

事实上,我想调用类似的函数数百次,我想知道那些“活”的计时器是否会影响性能。

我想以适当的方式停止或取消计时器对象。我做对了吗?

谢谢

4

2 回答 2

13

You should use the thread.join() to wait until your timer's thread is really finished and cleaned.

import threading

def ontimer():
    print threading.current_thread()

def main():
    timer = threading.Timer(2, ontimer)
    timer.start()
    print threading.current_thread()
    timer.cancel()
    timer.join()         # here you block the main thread until the timer is completely stopped
    if timer.isAlive():
        print "Timer is still alive"
    else:
        print "Timer is no more alive"
    if timer.finished:
        print "Timer is finished"


 if __name__ == "__main__":
main()

This will display :

<_MainThread(MainThread, started 5836)>
Timer is no more alive
Timer is finished
于 2012-06-18T13:31:11.550 回答
12

ATimer是 a 的子类,Thread它的实现非常简单。它通过订阅事件来等待提供的时间finished

因此,当您设置事件时,Timer.cancel可以保证不会调用该函数。但不保证 Timer 线程会直接继续(并退出)。

所以重点是timer的线程在执行完之后还可以存活cancel,但是函数不会被执行。所以检查finished是安全的,而在这种情况下,测试Thread.is_alive(较新的 API,使用这个!)是一种竞争条件。

time.sleep提示:您可以通过在调用后放置一个来验证这一点cancel。然后它只会打印:

<_MainThread(MainThread, started 10872)>
Timer is finished
于 2012-06-18T13:27:22.917 回答