fork vs threading.Thread

Alf P. Steinbach alfps at start.no
Sat Feb 13 05:25:23 CET 2010


* Jordan Apgar:
> I'm trying to run two servers in the same program at once.  Here are
> the two:
> class TftpServJ(Thread):
>     def __init__(self, ip, root, port=69, debug = False ):
>         Thread.__init__(self)
>         setup stuff here
> 
>     def run(self):
>         try:
>             self.server.listen(self.ip, self.port)
>         except KeyboardInterrupt:
>             pass
> 
> and
> class XMLServer(Thread):
>     def __init__(self, host, port, hostid, rsa_key):
>         Thread.__init__(self)
>          setup stuff
> 
>     def run(self):
>         self.server.serve_forever()
> 
> 
> I call them as:
> tftpserv = TftpServJ(host, "/home/twistedphrame/Desktop/xmlrpc_server/
> server")
> tftpserv.run()
> xmlserv = XMLServer(host, port, HostID, key)
> xmlserv.run()

Here you're just calling the tftpserv.run method directly, not on a separate thread.

So it blocks until it's finished (which probably is never?).

Instead, try using

   tftpserv.start()


According to the docs, "It [the start method] must be called at most once per 
thread object. It arranges for the object’s run() method to be invoked in a 
separate thread of control."

You may have to decide on how you want your program to terminate, if you want that.



> 
> 
> it seems that tftpserv runs but wont go on to spawn xmlserv as well.
> do I need to fork if I want both these to run at the same time?  It
> was my impression that by using Thread execution in the main program
> would continue.

See above.

Cheers & hth.,

- Alf



More information about the Python-list mailing list