Python多处理队列.get超时与睡眠

2024-09-24 00:28:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我用linux时间来计算5500和5000的循环时间,周期都是100毫秒,它们看起来很相似。在

代码段1:队列超时

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

片段二:有时间睡眠

^{pr2}$

代码段1是首选的,因为它不是休眠,然后检查毒丸队列,而是“休眠”检查队列。当然,这是一个相当不确定的点,因为周期通常只在0.100到0.500秒之间,但我不想确定在队列.get我错过了。在


Tags: 文档iotruehttpget队列queue代码段
1条回答
网友
1楼 · 发布于 2024-09-24 00:28:20

正如您所说,第一个选项是一个更好的选择,因为它不是无条件地休眠period,然后检查队列中是否有任何内容,然后再次睡眠,您在整个period中积极地等待某个内容进入队列,然后只是短暂地做一些事情而不是等待'!STOP!'到达。这里没有隐藏的gotchas;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()

相关问题 更多 >