[Twisted-Python] thread + signal + reactor.stop problem

Reza Lotun reza at getpeer.com
Fri Feb 13 04:59:42 EST 2009

Hi Gabriel,

There's two problems from what I can see.

1) You have a method run in a thread

    def __myLoop(self):
        while True:

but since it's being run in a thread, you need to schedule the call
into the reactor like so:

    def __myLoop(self):
        while True:
            reactor.callFromThread(self.transport.write, "Thread")

2) Your loop in that thread will run forever no matter what. It isn't
a daemon thread so there needs to be some sort of stopping criterion
(there's no way to kill Python threads externally):

    def __myLoop(self):
        while self.factory.running:
            reactor.callFromThread(self.transport.write, "Thread")

By setting an attribute on the factory in the __init__ called
'running' to True, then in the signal handler code we can set it to
False, providing a quick and dirty way to bail out of that thread.

I made the modifications and sending a cntrl-C made the program exit just fine.


On Fri, Feb 13, 2009 at 8:37 AM, Gabriel Rossetti
<gabriel.rossetti at arimaz.com> wrote:
> Hello everyone,
> I was able to write a small example that reproduces my problem, when I
> redefine signal and I have threads and I try to stop the reactor, it hangs.
> I wasn't sure if it was loopingCall or callLater or threads at first, but
> from my tests it's the threads that cause the problem. I attached the
> example, it's a modified version of the Twisted echo server/client example.
> Run the server, run the client, press Ctrl + C in the client's terminal (or
> Ctrl + break on windows) and it doesn't quit. I still have to test if it's
> caused by the signal redefinition at all or not.
> Thank you,
> Gabriel Rossetti
> _______________________________________________
> Twisted-Python mailing list
> Twisted-Python at twistedmatrix.com
> http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python

Reza Lotun
Senior Software Engineer
Peer Technologies Limited
reza at getpeer.com

More information about the Twisted-Python mailing list