我用非常標準的Threading.Event: 主線程獲取到一個點,它在運行一個循環:Python的更好的解決方案Threading.Event半忙等待
event.wait(60)
其他塊上直到一個答覆的要求可再啓動:
event.set()
我希望主線程,選擇40秒,但這種情況並非如此。 從Python 2.7源庫/ 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)
我們得到的是一個系統調用選擇運行每500US。 這會導致機器上的顯着負載,並且選擇循環相當緊密。
有人可以請解釋爲什麼有一個平衡的行爲,爲什麼它不同於等待文件描述符的線程。
第二,有沒有更好的方法來實現一個主要睡眠主線程沒有這樣一個緊密的循環?