我有一个线程将结果写入队列。
在另一个线程(GUI)中,我定期(在 IDLE 事件中)检查队列中是否有结果,如下所示:
def queue_get_all(q):
items = []
while 1:
try:
items.append(q.get_nowait())
except Empty, e:
break
return items
这样做好吗?
编辑:
I'm asking because sometimes the waiting thread gets stuck for a few seconds without taking out new results.
“卡住”问题原来是因为我在空闲事件处理程序中进行处理,而没有按照建议确保此类事件实际上是通过调用 wx.WakeUpIdle
生成的。
最佳答案
如果您总是从队列中取出所有可用项目,那么使用队列而不是仅使用带锁的列表是否有实际意义?即:
from __future__ import with_statement
import threading
class ItemStore(object):
def __init__(self):
self.lock = threading.Lock()
self.items = []
def add(self, item):
with self.lock:
self.items.append(item)
def getAll(self):
with self.lock:
items, self.items = self.items, []
return items
如果您还单独提取它们,并利用空队列的阻塞行为,那么您应该使用 Queue,但您的用例看起来要简单得多,并且上述方法可能会更好。
[Edit2] 我错过了一个事实,即您正在从空闲循环中轮询队列,并且从您的更新中,我发现问题与争用无关,因此以下方法与您的问题并不真正相关。我把它留了下来,以防万一有人发现这个有用的阻塞变体:
如果您确实想阻塞直到获得至少一个结果,您可以修改上述代码以等待数据通过生产者线程的信号变得可用。例如。
class ItemStore(object):
def __init__(self):
self.cond = threading.Condition()
self.items = []
def add(self, item):
with self.cond:
self.items.append(item)
self.cond.notify() # Wake 1 thread waiting on cond (if any)
def getAll(self, blocking=False):
with self.cond:
# If blocking is true, always return at least 1 item
while blocking and len(self.items) == 0:
self.cond.wait()
items, self.items = self.items, []
return items
关于python - 从线程队列中获取所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/156360/