[Tutor] Infinite Loops (and threads)

Luke Paireepinart rabidpoobear at gmail.com
Sun Dec 24 17:02:19 CET 2006


Kent Johnson wrote:
> Jonathan McManus wrote:
>   
>> Hi all,
>>
>> Just a quick question, really. Is there any good way to have an infinite
>> loop in a program, without said infinite loop eating up the CPU? I've
>> tried the trick of adding a pause (time.sleep(0.01)) somewhere in the
>> loop, and this appears to have worked on a basic infinite loop, but this
>> doesn't appear to work for two separate infinite loops (in threads).
>>     
>
> You would have to put a sleep in each thread.
>
> Why are you using infinite loops? Are you implementing some kind of 
> polling loop? Often there are better alternatives, either an event 
> notification or some kind of lock. If you post some details of why you 
> want to do this we may be able to help you find a better way.
>
> Kent
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   
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.

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,
so I tried this,

#code ----
self.conn.setblocking(False)
info = self.conn.recv(8000)#this should read everything.
#---- code

where conn is connected to another computer already,
and I get the following error:

(Verbatim except for line 3, changed to hide username/password)
Traceback (most recent call last):
  File "C:\Python Scripts\AIM Connection Server\toc2.py", line 199, in ?
    toc.login('---username---','---password---')
  File "C:\Python Scripts\AIM Connection Server\toc2.py", line 116, in login
    print self.getFlap()
  File "C:\Python Scripts\AIM Connection Server\toc2.py", line 93, in 
getFlap
    info = self.conn.recv(8000)#this should read everything.
error: (10035, 'The socket operation could not complete without blocking')

Do I misunderstand what blocking is?
It seems to me that blocking would mainly apply to inputs.
(My understanding is that 'blocking' means when you call 'recv' it will 
return '' if it didn't receive anything.)

I'd appreciate any links that I could read up on, or any advice on how 
to make socket inputs with event notification, as Kent mentioned earlier.

Basically, as Kent said, I have a polling loop, and I am not sure what 
the alternative is to threads.

Thanks,
-Luke


More information about the Tutor mailing list