[Tutor] Infinite Loops (and threads)

Kent Johnson kent37 at tds.net
Sun Dec 24 19:33:42 CET 2006

Luke Paireepinart wrote:

> Kent et. al.,
> I'm writing something that has to do with sockets.
> I need to recv any incoming packets from the socket.
> I will have potentially hundreds of separate sockets open in a single 
> application.
> I was just going to create a thread for each, so I could receive from 
> them separately.

Yes, that is one way to do it - make a thread for each socket and use 
blocking I/O. Then each thread will block until data is available. This 
avoids the kind of busy wait loop the OP described.
> Alternately, I figured I could read from each socket in sequence if I 
> could get the recv method to not block until it gets input,

That is another good approach. You might want to look at Twisted or 
Medusa, they are both server frameworks that use asynchronous, 
non-blocking I/O to manage multiple sockets in a single thread:

> Do I misunderstand what blocking is?
> It seems to me that blocking would mainly apply to inputs.

Usually, though output can block too.

> (My understanding is that 'blocking' means when you call 'recv' it will 
> return '' if it didn't receive anything.)

No; with a blocking socket, recv() will not return until data is 
available; with a non-blocking socket recv() will raise an exception if 
data is not available.


More information about the Tutor mailing list