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

Gabriel Rossetti gabriel.rossetti at arimaz.com
Fri Feb 13 05:21:20 EST 2009


Reza Lotun wrote:
> Hi Gabriel,
>   
Hello Reza,
> There's two problems from what I can see.
>
> 1) You have a method run in a thread
>
>     def __myLoop(self):
>         while True:
>             self.transport.write("Thread")
>             time.sleep(1)
>
> 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")
>             time.sleep(1)
>
>   

Yes, I forgot to do that in the example, silly me, I do do that in my 
real code though.

> 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")
>             time.sleep(1)
>
> 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.
>
>   

Ahh, ok, I though Twisted would stop them somehow, That must be it then 
one of my threads must not exit and thus runs forever and Twisted waits 
on it.

> I made the modifications and sending a cntrl-C made the program exit just fine.
>
> Cheers,
> Reza
>   

Thank you!
Gabriel

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




More information about the Twisted-Python mailing list