threading

Frank Millman frank at chagford.com
Thu Apr 10 07:10:54 EDT 2014


"Chris Angelico" <rosuav at gmail.com> wrote in message 
news:CAPTjJmoWaHPZk=DAxbfJ=9ez2aj=4yf2C8WMbRYoF5VgN6Exsw at mail.gmail.com...
> On Thu, Apr 10, 2014 at 7:17 PM, Frank Millman <frank at chagford.com> wrote:
>> The current version of my program uses HTTP. As I understand it, a client
>> makes a connection and submits a request. The server processes the 
>> request
>> and returns a result. The connection is then closed.
>>
>> In this scenario, does async apply at all? There is no open connection to
>> 'select' or 'poll'. You have to ensure that the request handler does not
>> block the entire process, so that the main loop is ready to accept more
>> connections. But passing the request to a thread for handling seems an
>> effective solution.
>


[...]

Thanks, Chris - I am learning a lot!

I have skipped the first part of your reply, as it seems to refer to the 
client. I am using a web browser as a client, so I don't have to worry about 
programming that.

>
> When you write the server, you effectively have the same principle,
> with one additional feature: a listening socket becomes readable
> whenever someone connects. So you can select() on that socket, just
> like you can with the others, and whenever there's a new connection,
> you add it to the collection and listen for requests on all of them.
> It's basically the same concept; as soon as you can accept a new
> connection, you do so, and then go back to the main loop.
>

This is where it gets interesting. At present I am using cherrypy as a 
server, and I have not checked its internals. However, in the past I have 
dabbled with writing server programs like this -

    while self.running:
        try:
            conn,addr = self.s.accept()
            Session(args=(self, conn)).start()
        except KeyboardInterrupt:
            self.shutdown()

In this scenario, the loop blocks on 'accept'.

You seem to be suggesting that I set the socket to 'non-blocking', use 
select() to determine when a client is trying to connect, and then call 
'accept' on it to create a new connection.

If so, I understand your point. The main loop changes from 'blocking' to 
'non-blocking', which frees it up to perform all kinds of other tasks as 
well. It is no longer just a 'web server', but becomes an 'all-purpose 
server'.

Much food for thought!

Frank






More information about the Python-list mailing list