Python Event :: wait with timeout给出了延迟

时间:2014-02-14 12:16:18

标签: python performance

在Windows 7和Server 2012上运行Python 2.6和2.7

事件::等待因使用未触发的超时而导致延迟,因为事件是及时设置的。我不明白为什么。

有人可以解释一下吗?

以下程序显示了这一点并给出了可能的解释;

'''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) 

1 个答案:

答案 0 :(得分:2)

查看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毫秒之前睡觉结束)。