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?

deeshank
  • 4,286
  • 4
  • 26
  • 32

1 Answers1

1

To do what you want by deferring to a thread:

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()

To do what you want asynchronously, which is how Twisted is designed, you could do:

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()

which is considerably neater and doesn't use any threads. In both cases you have to take care of stopping the event loop (reactor) once your function has finished (that's what the reactor.stop() callback is for), otherwise your program will just block.

Paul Weaver
  • 284
  • 5
  • 9