how do I listen on a socket without sucking up all the CPU time?

Donn Cave donn at u.washington.edu
Tue Oct 3 12:03:19 EDT 2000


Quoth "Joshua Muskovitz" <josh at open.com>:
|> Why is the socket set to non-blocking?  Why not set it to
|> blocking so that the thread blocks until there's data to read?
|
| This is one of those "um" questions.  The answer is "um, well, the prototype
| code I was given to start with set it to non-blocking."  <insert sheepish
| grin here>
|
| The only reason I can thing of is that a separate thread needs to be able to
| use the same socket to send requests (send and recv operate on the same
| socket in different threads), but this may not be a valid reason either.

Now that you have select() working, there's no reason to make the socket
non-blocking.  I have never understood the attraction of non-blocking
I/O.  In a well designed program it never seems to be needed, and it often
appears in places where it is not apparently used.

I have had some trouble with concurrent I/O on a single socket in multiple
threads.  I think concurrent access to any device is asking for trouble.

| select.select worked great, but now I've got other problems, namely
| figureing out why I'm no longer catching the KeyboardInterrupt exception I
| used to be able to catch.

Note that signals can be delivered only to the main thread, and as
already mentioned in another followup, the handler doesn't execute
immediately at the C level, but rather immediately at the Python level,
which could really be a long time later.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list