【发布时间】:2012-03-31 07:53:40
【问题描述】:
我正在使用非常标准的 Threading.Event: 主线程到达一个循环运行的点:
event.wait(60)
其他人阻止请求,直到回复可用,然后启动:
event.set()
我希望主线程选择 40 秒,但事实并非如此。 来自 Python 2.7 源代码 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)
我们得到的是每 500us 运行一次选择系统调用。 这会在具有非常紧密的选择循环的机器上造成明显的负载。
有人能解释一下为什么涉及到平衡行为,为什么它与等待文件描述符的线程不同。
其次,有没有更好的方法来实现一个大部分处于休眠状态的主线程而没有如此紧密的循环?
【问题讨论】:
标签: python multithreading python-2.7 events busy-loop