在 Windows 7 和 Server 2012 上运行 Python 2.6 和 2.7
Event::wait 与未触发的超时一起使用时会导致延迟,因为事件已及时设置。我不明白为什么。
谁能解释一下?
下面的程序展示了这一点并给出了可能的解释;
'''Shows that using a timeout in Event::wait (same for Queue::wait) causes a
delay. This is perhaps caused by a polling loop inside the wait implementation.
This polling loop sleeps some time depending on the timeout.
Probably wait timeout > 1ms => sleep = 1ms
A wait with timeout can take at least this sleep time even though the event is
set or queue filled much faster.'''
import threading
event1 = threading.Event()
event2 = threading.Event()
def receiver():
'''wait 4 event2, clear event2 and set event1.'''
while True:
event2.wait()
event2.clear()
event1.set()
receiver_thread = threading.Thread(target = receiver)
receiver_thread.start()
def do_transaction(timeout):
'''Performs a transaction; clear event1, set event2 and wait for thread to set event1.'''
event1.clear()
event2.set()
event1.wait(timeout = timeout)
while True:
# With timeout None this runs fast and CPU bound.
# With timeout set to some value this runs slow and not CPU bound.
do_transaction(timeout = 10.0)
最佳答案
查看 threading.Condition 类的 wait() 方法的源代码,有两个截然不同的代码路径。没有超时,我们只是永远等待一个锁,当我们得到锁时,我们立即返回。
但是,有了超时,您不能简单地永远等待锁,低级锁不提供超时实现。所以代码休眠的时间呈指数级增长,每次休眠后检查是否可以获取锁。代码中的相关注释:
# 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).
因此,在短时间内无法通知条件/事件的平均情况下,您会看到 25 毫秒的延迟(随机传入事件平均会在最大休眠时间 50 毫秒之前到达一半) sleep 结束)。
关于Python Event::wait with timeout 给出延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21779183/