为什么这个Python脚本要等到计时器线程执行完才继续?
from threading import Timer
def startTimer():
t = Timer(10.0, foo, ['hello world', 'tell me more'] )
t.start()
print 'Timer function invoked'
print 'function exit'
def foo(msg, msg2):
print 'foo was executed'
print msg
print msg2
if __name__ == '__main__':
startTimer()
print 'end of program'
我把上面的代码保存到了一个文件里(叫做timer.py),然后在命令行中输入了python timer.py。但是它一直等到foo()这个函数执行完才继续往下走。这是为什么呢?这种行为或者执行方式叫什么呢?
1 个回答
20
定时器其实就是一个线程,而Python在停止运行时会等所有非daemonic
线程结束。
线程可以被标记为“守护线程”。这个标记的意思是,当程序中只剩下守护线程时,整个Python程序就会退出。这个标记的初始值是从创建它的线程那里继承来的。你可以通过守护属性来设置这个标记。
如果你设置the_timer.daemon=True
,那么Python会立刻退出,而不是等定时器结束。