问题描述
我有一个进程间队列,它通常是空的,并且偶尔会出现一些东西.在我的一个线程中,我想像这样定义一个 while 循环:
I have an inter-process queue that is usually empty and only once in a while does something appear in it. In one of my threads I want to define a while loop like this:
def mythread(queue1):
while (queue1.get_nowait() != 1):
#do stuff
这很好用,直到队列为空,这在我的情况下很快发生.当队列为空时,调用 get_nowait() 或 get(False) 会引发空队列异常.有没有什么方法可以在不阻塞和不引发空异常的情况下检查队列?
This works great until the queue is empty which happens quickly in my case. When the queue is empty calling get_nowait() or get(False) raises the empty queue exception. Is there any way to check the queue without blocking AND without raising the empty exception?
推荐答案
使用empty
方法
if queue1.empty():
pass
else:
# get items from the queue
注意:医生说不可靠"(不是开玩笑).
Note: doc says "not reliable" (no kidding).
我想那是因为它可以在发布消息时返回 True
(队列为空),所以操作不像捕获异常那样原子.好吧,然后是一个 get_nowait()
调用我想除非其他线程也可以使用队列,否则这无关紧要,在这种情况下可能会发生竞争条件并且队列可能为空尝试从中阅读!
I suppose that's because it can return True
(queue is empty) while a message is posted, so the operation is not as atomic as catching the exception. Well, followed by a get_nowait()
call I suppose it doesn't matter unless some other thread can consume the queue as well, in which case a racing condition could occur and the queue could be empty when you try to read from it!
这篇关于在 python 中使用 get_nowait() 而不引发空异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!