[Twisted-Python] Run Twisted reactor from a Thread

Adi Roiban adi at roiban.ro
Tue Feb 3 08:47:22 MST 2015


On 3 February 2015 at 14:41, Abdelhalim Kadi <kadi.halim at gmail.com> wrote:
> Hello;
>
> When i run reactor from thread in a synchrone python program, the twisted
> code is never called.
>
> To resolve this problem, I had to put a sleep.
>
> def _reactor_thread(self):
>     if not self.reactor.running:
>         self.reactor.run(installSignalHandlers=0)
>
>
> def _start_thread( self ):
>
>     self.client_thread = Thread( target=self._reactor_thread,
>                                  name="mine" )
>     self.client_thread.setDaemon(True)
>     self.client_thread.start()
>     from time import sleep
>     sleep( 0.5 )
>
> What is the best way to do it, instead of calling sleep?


In case Crochet is does not you maybe you can use
addSystemEventTrigger with 'startup' and 'after' to have a something
called after startup.

http://twistedmatrix.com/documents/14.0.0/api/twisted.internet.interfaces.IReactorCore.html#addSystemEventTrigger

When you want to stop the reactor, make sure you call it from the
right thread using reactor.callFromThread(reactor.stop)
You can use addSystemEventTrigger to hook into the reactor shutdow process.

-- 
Adi Roiban




More information about the Twisted-Python mailing list