I'm using pretty standard Threading.Event: Main thread gets to a point where its in a loop that runs:
event.wait(60)
The other blocks on a request until a reply is available and then initiates a:
event.set()
I would expect the main thread to select for 40 seconds, but this is not the case. From the Python 2.7 source Lib/threading.py:
# 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. The scheme here sleeps very
# little at first, longer as time goes on, but never longer
# than 20 times per second (or the timeout time remaining).
endtime = _time() + timeout
delay = 0.0005 # 500 us -> initial delay of 1 ms
while True:
gotit = waiter.acquire(0)
if gotit:
break
remaining = endtime - _time()
if remaining <= 0:
break
delay = min(delay * 2, remaining, .05)
_sleep(delay)
What we get is a select syscall run every 500us. This causes noticeable load on the machine with a pretty tight select loop.
Can someone please explain why there is a balancing act involved and why is it different than a thread waiting on a file descriptor.
and second, Is there a better way to implement a mostly sleeping main thread without such a tight loop?