Python Event::wait with timeout 给出延迟

标签 python performance

在 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/

相关文章:

python - 高效的 Django 查询

python - 如何在 python 中修补模拟来自操作系统的多个调用?

Java RCaller 重用一个函数

python - 带有批量插入的 peewee 进入 sqlite db 非常慢

performance - 加速 gz 文件上的 sed

java - GET 如何符合高性能 Web 应用程序的黄金法则?

python - 如何在 python 中修改 html 树?

迭代元组移位列表的 Pythonic 方法

python - 损坏的 DAG : [/usr/local/airflow/dags/dag_1_V5. py] 无法在 Airflow 上导入名称 opentype

python - 列表上的 Django lte/gte 查询