【问题标题】:Python Threading Timer and Event objectsPython 线程定时器和事件对象
【发布时间】:2018-01-29 06:08:18
【问题描述】:

代码:

from threading import Timer, Event
from time import sleep

def hello(e):
    print e
    print 'Inside......'
    while True:
        if e.isSet():
            print "hello_world"
            break

if __name__ == '__main__':
    e = Event()
    t = Timer(1, hello(e,))
    t.start()
    print e.isSet()
    sleep(2)
    e.set()
    print e.isSet()

输出:

 [root@localhost ~]# python test_event.py 
<threading._Event object at 0x7f440cbbc310>
Inside......

在上面的代码中,我试图从 python 中理解 Timer and, Event 对象。如果我运行上面的代码,Timer 会调用函数hello() 并且它会无限期地运行。主线程没有执行t.start() 旁边的行。我在这里想念什么?

谢谢。

【问题讨论】:

标签: python multithreading events timer


【解决方案1】:

在您的代码中,

t = Timer(1, hello(e,))

您在创建线程之前调用函数,而不是向线程传递参数。 hello(e,) 调用等待事件e 设置的函数。由于它在这里陷入了无限循环并且没有从函数hello 返回,因此没有发生线程创建并且永远不会设置e

只需将其更改为有效的线程创建:

t = Timer(1, hello, [e])

【讨论】:

  • 非常感谢您清楚地解释它。
猜你喜欢
  • 1970-01-01
  • 2011-12-09
  • 2016-09-23
  • 1970-01-01
  • 2014-01-21
  • 2018-11-16
  • 2011-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多