nova team mailing list archive
-
nova team
-
Mailing list archive
-
Message #00150
Re: Why not python threads?
Hey Soren,
> def wait_a_little_bit(d):
> time.sleep(2)
> d.callback("Slept until %s" % (time.asctime()))
>
> def do_stuff():
> logging.basicConfig(level=logging.INFO)
>
> d = defer.Deferred()
> d.addCallback(logging.info)
> reactor.callInThread(wait_a_little_bit, d)
You can't really do this, unfortunately, because the Twisted core is
not thread-safe.
The right approach is to either:
a) Use deferToThread(), and simply return the value you want from the
function. The deferred will be fired with the result once it's done.
b) Use the same logic you used above, but use
reactor.callFromThread(d.callback, result) from within the thread, so
that the callback happens within the main thread in due time.
Option (a) is generally the most elegant, and actually uses option (b)
internally, but deals with the boredom for you.
--
Gustavo Niemeyer
http://niemeyer.net
http://niemeyer.net/blog
http://niemeyer.net/twitter
Follow ups
References