newbie question on threading

Aahz aahz at pythoncraft.com
Mon Oct 14 00:42:07 EDT 2002


In article <7cpjqugerih8sos23strcsftgt53tbs8lo at 4ax.com>,
Gonçalo Rodrigues  <op73418 at mail.telepac.pt> wrote:
>On 13 Oct 2002 02:32:32 -0400, aahz at pythoncraft.com (Aahz) wrote:
>>In article <jsngquskdhc0cpg867djcna0cl6u8tlm9l at 4ax.com>,
>>Gonçalo Rodrigues  <op73418 at mail.telepac.pt> wrote:
>>>
>>>#Balancing act: We can't afford a pure busy loop, so we
>>>#have to sleep; but if we sleep the whole timeout time,
>>>#we'll be unresponsive.
>>>
>>>My question is: why is a busy loop not affordable (without a sleep
>>>call), e.g. something like (in pseudo-code description)
>>>
>>>while 1:
>>>    <acquire lock>
>>>    if <acquire sucessfull>:
>>>        break
>>>    if <timedout?>:
>>>        break
>>>    <calculate endtime>
>>
>>Consider this:
>>
>>    while 1:
>>        pass
>>
>>Given the above loop in a thread, how much useful work is the thread
>>doing?  Not much, right?  Well, adding an "if" statement to the loop
>>doesn't do any good for producing useful work.
>
>I must be missing something but I am not understanding. Isn't that what
>the wait method is supposed to do? Put the thread dormant, waiting until
>you get timedout or you can acquire the lock? The only difference
>between the pseudo-loop I wrote above and the one in the threading
>module is a call to to time.sleep - and that is the core of my question,
>why even bother to add the sleep call? Why not just a pure simple busy
>loop? Why can't we afford it?

Note carefully that I said "useful work".  The point is that a busy loop
consumes CPU resources, but it is *NOT* doing useful work, and in
consuming those CPU resources, it is keeping other threads from doing
useful work.  Because time.sleep() causes an OS-level block, other
threads can run during the time.sleep().  The problem is a tradeoff
between the delay in response caused by calling time.sleep() versus the
amount of CPU time consumed by the busy loop.

In fact, you shouldn't even be using condition objects in the first
place, IMO.  Figure out a way to use a Queue, and your application will
almost certainly be both more efficient *and* more responsive.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

Project Vote Smart: http://www.vote-smart.org/



More information about the Python-list mailing list