Unexpected (?) Thread behaviour

Peter Hansen peter at engcorp.com
Fri May 2 23:59:44 EDT 2003


Vincent Berg wrote:
> 
> class ServerThread(Thread):
>     def __init__(self):
>         Thread.__init__(self)
>         self.clients = []
> 
>     def run(self):
>         while 1:
>             if len(self.clients) > 0:
>                 rd, wd, ex = select.select(self.clients, [], [], None)
>                 for n in rd:
>                     n.handle()

Among other things, this is not what you want to do....

The above while loop will do a "busy-wait", consuming all the available
CPU time (except for when Python switches to another thread) waiting
for self.clients to get something in it.

At least put a "time.sleep(0.005)" or something after the if statement.

> So my actual question is: why doesn't the run() method notices that
> self.clients is updated?? Shouldn't it notice it?? 

Well, what you think is happening probably is not.  Certainly the code
you posted should show that self.clients is getting appended to.  Why
do you think it is not?  Have you tried inserting a print statement
in the while loop after the if, to show what self.clients contains just
before the select statement?  You might learn something about what's
really happening by instrumenting your code a little more.

-Peter




More information about the Python-list mailing list