[Twisted-Python] A thread in isolation
Jason Rennie
jrennie at gmail.com
Thu Feb 17 15:59:01 MST 2011
What's the larger problem you're trying to solve?
Jason
On Thu, Feb 17, 2011 at 4:38 PM, <Andy.Henshaw at gtri.gatech.edu> wrote:
> I apologize in advance – another question about Twisted and threading. I
> just seem to have trouble with this and I’m hoping my example is simple
> enough that a good explanation will be forthcoming.
>
>
>
> I’m trying to start and stop Twisted in its own thread, over and over.
> I’ve seen some notes that say this is a bad idea and that programs that do
> so should be restructured. But, it would really work better for this
> application if I could do it somehow.
>
>
>
> My controlling thread just wants to start Twisted, let it do its thing, and
> then let the thread stop. Later on, I’d like to do it again. In the
> example code below, the thread runs and stops fine in the first iteration.
> In the second iteration, it starts, seems to run okay, but it never stops.
> Is this an unreasonable request?
>
>
>
> from threading import Thread
>
> from twisted.internet import reactor
>
> from twisted.internet import protocol
>
>
>
> PORT = 9999
>
>
>
> class AgentManager(Thread):
>
> def run(self):
>
> print '\nstarting agentmanager', self
>
>
>
> reactor.connectTCP('localhost', PORT, AgentClientFactory())
>
> reactor.listenTCP(PORT, AgentServerFactory())
>
>
>
> reactor.callLater(5, reactor.stop)
>
> reactor.run(installSignalHandlers=0)
>
>
>
>
>
> class Producer(protocol.Protocol):
>
> def connectionMade(self):
>
> print 'connection made'
>
> self.transport.write('Hello')
>
>
>
> def connectionLost(self, reason):
>
> print 'connection lost'
>
>
>
>
>
> class Consumer(protocol.Protocol):
>
> def dataReceived(self, data):
>
> print data
>
>
>
> class AgentServerFactory(protocol.ServerFactory):
>
> protocol = Producer
>
>
>
>
>
> class AgentClientFactory(protocol.ClientFactory):
>
> protocol = Consumer
>
>
>
>
>
> if __name__ == '__main__':
>
> for i in range(3):
>
> mgr = AgentManager()
>
> mgr.start()
>
> mgr.join()
>
> _______________________________________________
> Twisted-Python mailing list
> Twisted-Python at twistedmatrix.com
> http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python
>
>
--
Jason Rennie
Research Scientist, ITA Software
617-714-2645
http://www.itasoftware.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: </pipermail/twisted-python/attachments/20110217/9035114a/attachment.html>
More information about the Twisted-Python
mailing list