[Twisted-Python] deferToThread()

Lenny G Arbage alengarbage at yahoo.com
Sat Mar 12 11:58:40 EST 2005

Answer: the example seems to be incomplete.  The
following changes make things work:

from twisted.internet import reactor, threads
def doLongCalculation(y):
  print "returning from doLongCalc"
  return 3
def printResult(x):
  print "deferred returned "+str(x)
d = threads.deferToThread(doLongCalculation, 4)
print "just waiting for deferred..."

  It isn't clear from the docs that deferToThread
relies on reactor.run() -- the howto states "The
utility methods are not part of the
twisted.internet.reactor APIs, but are implemented in
twisted.internet.threads".  But now, it seems
perfectly clear to me now that, "of course you need
the reactor."   Maybe the examples in the howto should
be updated to make this more clear?  It wasn't until I
found a snippet of code at
http://pig.slug.org.au/talks/Twisted2/slides.html that
I was able to sort this out.

  -- Lenny G

--- Lenny G Arbage <alengarbage at yahoo.com> wrote:
> Can someone explain why the following example
> (lifted
> straight out of
> doesn't work?
> from twisted.internet import threads
> def doLongCalculation():
>   #time.sleep(3)
>   return 3
> def printResult(x):
>   print "deferred returned "+str(x)
> d = threads.deferToThread(doLongCalculation)
> d.addCallback(printResult)
> print "just waiting for deferred..."
> Running the above, with or without time.sleep(),
> results in a hanging process.  When run "just
> waiting
> for deferred..." prints but the callback is never
> invoked and the process hangs.
> I'm using twisted 1.3, python 2.3.4 under Linux
> (FC3).
>   Lenny G

Do you Yahoo!? 
Yahoo! Small Business - Try our new resources site!

More information about the Twisted-Python mailing list