[Twisted-Python] Threading examples...
Andrew Bennetts
andrew-twisted at puzzling.org
Tue Mar 23 18:10:53 EST 2004
On Tue, Mar 23, 2004 at 03:58:20PM -0700, William McLendon wrote:
> Thanks,
>
> So, now my example looks like this:
>
> import time
> from twisted.internet import reactor
>
> def aSillyBlockingMethod(x):
> time.sleep(2)
> print x
> reactor.callFromThread(reactor.stop)
>
> # run method in thread
> reactor.callInThread(aSillyBlockingMethod, "2 seconds have passed")
>
>
> It still just hangs... I have to go kill it from another window after
> getting its pid from ps. Am I doing the reactor.stop thing correctly?
Heh. I just noticed the real bug: that example doesn't call reactor.run(),
either.
Complete, working example:
----
import time
from twisted.internet import reactor
def aSillyBlockingMethod(x):
time.sleep(2)
print x
reactor.callFromThread(reactor.stop)
# run method in thread
reactor.callInThread(aSillyBlockingMethod, "2 seconds have passed")
reactor.run()
----
That reactor.callInThread starts the thread when the reactor isn't running yet
is probably a bug in Twisted.
> Basically, I have an application that talks via a http interface to a user
> and I need to spawn off and do stuff from time to time. I'm still learning
> how all the reactor eventloops and whatnot work. I ran into a problem
> where I'm trying to run something via
> twisted.internet.protocol.ProcessProtocol and serve its results up from
> within a reactor.listentTCP() page handler ... but it blew up. So, I'm
How did it blow up (and how are you spawning the process)? Twisted is quite
capable of coping with this -- it's how the CGI support in twisted.web
works.
> thinking that I could maybe just fork it off and run that way. I've been
> trying to figure out how the reactors() work and the threading and whatnot
> the last few days but am kind of finding little help in the docs and google
> that is at my level of understanding... seems most of the stuff is snippets
> and pieces that assume you already see the big picture :-( Any help here
> is greatly appreciated ;-)
I strongly advise avoiding threads unless you really need them. From your
description of what you are trying to do, you don't need them.
-Andrew.
More information about the Twisted-Python
mailing list