newbie question on threading
Gonçalo Rodrigues
op73418 at mail.telepac.pt
Mon Oct 14 08:06:03 EDT 2002
On 14 Oct 2002 00:42:07 -0400, aahz at pythoncraft.com (Aahz) wrote:
>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.
Thanks, I understand it now.
>
>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.
And I am not. I am writing a small multithreaded app where the child
threads dish out data precisely by pushing it into a Queue "owned" by
the father thread.
Once again, thanks for the explanation,
Gonçalo Rodrigues
More information about the Python-list
mailing list