【问题标题】:Python multiprocessing queue.get with timeout vs sleepPython multiprocessing queue.get 超时与睡眠
【发布时间】:2014-07-12 14:41:06
【问题描述】:

我找不到关于 python 队列 get with timeout: get([block[, timeout]]) 的任何文档,而在 http://www.pythoncentral.io/pythons-time-sleep-pause-wait-sleep-stop-your-code/ 有关于 python 的 time.sleep() 的良好文档。

我已经使用 linux 时间来计时 5、500 和 5000 的循环,周期为 100 毫秒,它们看起来都相似。

片段 1:队列超时

while True:
    try:
        if self._queue.get(True,period) == '!STOP!: break
    except:
        # Queue.Empty session, keep going
        -- do stuff here --

片段 2:随着时间的推移睡眠

while True:
    try:
        if self._queue.get_nowait() == '!STOP!: break
    except:
        # Queue.Empty session, keep going
        -- do stuff here --
        time.sleep(period)

片段 1 是首选,因为它不是休眠,然后检查毒丸队列,而是“休眠”检查队列。当然,这是一个非常有争议的问题,因为该时间段通常只会在 0.100 到 0.500 秒之间,但我不能确保队列中没有任何东西。get 我错过了。

【问题讨论】:

  • 你有什么问题?您是否阅读过get() 方法的文档?描述有什么不清楚的地方?
  • 我做了,但没有描述 get 中使用了哪些底层方法。在 time.sleep 中,使用了 unix gettimeofday(如果可用)。我不需要 rt 但希望从文档中尽可能接近,我可以从 time.sleep 中得到,但使用 get() 我不知道正在使用什么,以及是否有可能在引擎盖下发生的事情可以抢占导致提前或延迟抛出一个空的 esception

标签: python timeout multiprocessing sleep


【解决方案1】:

正如您所说,第一个选项是更好的选择,因为您不是无条件地为period 休眠,然后检查队列中是否有任何东西,然后再次休眠,您正在积极等待某事put 进入整个period 的队列,然后只是简单地做一些事情,而不是等待'!STOP!' 到达。没有隐藏的陷阱; get_nowait 在内部使用 time.time() + period 来决定等待多长时间 1) 能够获取队列上的内部锁,以及 2) 实际在队列中获取的东西。这是来自multprocessing/queues.py的相关代码:

    if block:
        deadline = time.time() + timeout
    if not self._rlock.acquire(block, timeout): # Waits for up to `timeout` to get the lock
        raise Empty # raise empty if it didn't get it
    try:
        if block:
            timeout = deadline - time.time()
            if timeout < 0 or not self._poll(timeout): # Once it has the lock, waits for however much time is left before `deadline` to something to arrive
                raise Empty
        elif not self._poll():
            raise Empty
        res = self._recv()
        self._sem.release()
        return res 
    finally:
        self._rlock.release()

【讨论】:

  • 我想我应该在问之前先去看代码:)
猜你喜欢
  • 1970-01-01
  • 2012-04-07
  • 2013-08-17
  • 2012-05-17
  • 2013-01-13
  • 2010-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多