Using thread in an asyncronous application

Giampaolo Rodola' gnewsg at gmail.com
Sat Nov 29 12:27:38 CET 2008


On 29 Nov, 02:24, Aaron Brady <castiro... at gmail.com> wrote:
> On Nov 27, 9:03 am, "Giampaolo Rodola'" <gne... at gmail.com> wrote:
>
>
>
>
>
> > Hi,
> > I'm the maintainer of an asynchronous FTP server implementation based
> > on asyncore.
> > Some days ago I thought it would be interesting to add a class
> > offering the possibility to run the asyncore loop into a thread so
> > that a user can run the server without blocking the entire
> > application.
> > It could be useful, for example, in case someone wants to integrate a
> > GUI.
>
> > Since I'm not good with multi-threaded programming I'd like some
> > opinions about the code I'm going to paste below.
>
> > The FTPServer class that I inherited in my subclass is the
> > "dispatcher" which listens on port 21 dispatching the incoming
> > connection to an "handler".
> > The polling loop (FTPServer.serve_forever()) is wrapped in the run
> > method.
> > As you can see I acquire and release the lock (threading.Lock) every
> > time I call the polling loop.
> > My question is: is that really necessary?
> > Should I expect some weird behavior by running the main loop into a
> > thread like I did?
>
> > Thanks in advance
>
> I found it hard to read through it.  Do you have a smaller abstract
> example?- Nascondi testo citato
>
> - Mostra testo citato -

Yeah, sure. I removed all the confusing stuff. Though I didn't tried
it it should work:


class ThreadedFTPServer(FTPServer, threading.Thread):

    def __init__(self, address, handler):
        FTPServer.__init__(self, address, handler)
        threading.Thread.__init__(self)
        self.__serving = False

    def start(self):
        threading.Thread.start(self)

    def run(self):
        self.__serving = True
        while self.__serving:
            self.__lock.acquire()
            FTPServer.serve_forever(self, timeout=1, count=1)
            self.__lock.release()
        FTPServer.close_all(self, ignore_all=True)

    def stop(self):
        if not self.__serving:
            raise RuntimeError("Server not started yet")
        self.__serving = False
        self.join()


--- Giampaolo
http://code.google.com/p/pyftpdlib/



More information about the Python-list mailing list