[Asterisk-Dev] busy-wait loops in pbx_dundi
Steve Kann
stevek at stevek.com
Fri Jun 10 06:55:59 MST 2005
Luigi Rizzo wrote:
>On Fri, Jun 10, 2005 at 07:59:40AM -0400, SteveK wrote:
>
>
>>On Jun 10, 2005, at 4:53 AM, Luigi Rizzo wrote:
>>
>>
>>
>>>while applying the timeval changes, i noticed that pbx_dundi.c
>>>is full of busy-wait loops of the form
>>>
>>> while (!some_condition) {
>>> usleep(1);
>>> }
>>>
>>>could someone comment how one avoids that this code eats 100% of the
>>>CPU and how high the risk is ?
>>>
>>>
>>The answer to that seems pretty obvious, Luigi.
>>
>>Assuming that usleep works correctly (it more or less does), and the
>>test for some condition takes less than a microsecond to execute (it
>>surely does), then this loop won't use more than 0.1% of your CPU.
>>
>>
>
>you are assuming that the interval is rounded up to the timer tick
>which i see mentioned as a possibility on manual pages but not as
>a mandatory behaviour. Never mind that linux or freebsd does so, you
>cannot tell what some different kernel does.
>(you are also assuming the tick to be >= 1ms, but that's a minor point),
>
>To me this code seems unsafe.
>If we are happy with the code sleeping for 1ms then we should
>write usleep(1000) not usleep(1).
>
>In any case my point was to figure out how quickly are we interested
>in responding to those event, and putting a sensible value in
>the timeout.
>
>
DOH! I had an off by 1000 error on my head :) -- was thinking that
usleep took milli, not micro-seconds.
In general, though, usleep(1) will at the very least cause a thread to
yield, even if it doesn't wait until the next timer tick to get
re-activated. If the condition is waiting for some kind of lock, which
presumably isn't being held by something blocking on i/o, then that kind
of loop doesn't seem dangerous..
-SteveK
More information about the asterisk-dev
mailing list