0

I am new to Twisted framework, and I would like to make the program wait for the deferred thread to complete.

import time
from twisted.internet import defer, threads

a=None
def proc(n):
    time.sleep(n)
    print "Hi!!"
    a=1
    return 

d = threads.deferToThread(proc,5)
while not a:
    pass
print a
print "Done"

Is it possible to wait for the deferred to complete in a neat way rather than looping like this?

4

1 回答 1

1

通过推迟到一个线程来做你想做的事:

import time
from twisted.internet import threads, reactor

def proc(n):
    time.sleep(n)
    print "Hi!!"

d = threads.deferToThread(proc, 5)
d.addCallback(lambda _: reactor.stop())
reactor.run()

要异步执行您想要的操作,这就是 Twisted 的设计方式,您可以执行以下操作:

from twisted.internet import task, reactor

def say_hi():
    print 'Hi'

d = task.deferLater(reactor, 5, say_hi)
d.addCallback(lambda _: reactor.stop())
reactor.run()

这相当整洁并且不使用任何线程。在这两种情况下,您都必须注意在reactor函数完成后停止事件循环 ( )(这就是reactor.stop()回调的用途),否则您的程序将阻塞。

于 2014-09-07T23:11:42.227 回答