为什么这个python脚本会等到执行定时器线程?

[英]why does this python script wait till the timer thread is executed?


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'

I've saved the above code in a file (timer.py), and then typed python timer.py in the shell. But it waited until foo() was executed. Why is this so? What do you call this behaviour/style of execution?

我已将上述代码保存在文件(timer.py)中,然后在shell中键入python timer.py。但它一直等到foo()被执行。为什么会这样?你怎么称呼这种行为/执行方式?

1 个解决方案

#1


14  

Timer is just a thread and Python waits for all non-daemonic threads before stopping the interpreter.

Timer只是一个线程,Python在停止解释器之前等待所有非守护程序线程。

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property.

线程可以标记为“守护程序线程”。这个标志的意义在于当只剩下守护进程线程时整个Python程序退出。初始值继承自创建线程。可以通过守护程序属性设置该标志。

from the docs

来自文档

Set the_timer.daemon=True and Python will exit right away instead of waiting for the timer.

设置the_timer.daemon = True,Python将立即退出,而不是等待计时器。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2010/12/25/b5a365887cbd874633cd01a1e4a9b6dc.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号