从线程队列中获取所有项目 [英] Get all items from thread Queue

查看:61
本文介绍了从线程队列中获取所有项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程将结果写入队列.

I have one thread that writes results into a Queue.

在另一个线程(GUI)中,我定期(在IDLE事件中)检查队列中是否有结果,如下所示:

In another thread (GUI), I periodically (in the IDLE event) check if there are results in the queue, like this:

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实际上生成了此类事件.

The "stuck" problem turned out to be because I was doing the processing in the idle event handler, without making sure that such events are actually generated by calling wx.WakeUpIdle, as is recommended.

推荐答案

如果get_nowait()调用由于列表为空而不返回而引起暂停,我会感到非常惊讶.

I'd be very surprised if the get_nowait() call caused the pause by not returning if the list was empty.

是否可能在两次检查之间发布了大量(也许很大?)项目,这意味着接收线程有大量数据要从Queue中提取?您可以尝试限制一批检索的数量:

Could it be that you're posting a large number of (maybe big?) items between checks which means the receiving thread has a large amount of data to pull out of the Queue? You could try limiting the number you retrieve in one batch:

def queue_get_all(q):
    items = []
    maxItemsToRetreive = 10
    for numOfItemsRetrieved in range(0, maxItemsToRetreive):
        try:
            if numOfItemsRetrieved == maxItemsToRetreive:
                break
            items.append(q.get_nowait())
        except Empty, e:
            break
    return items

这将限制接收线程一次最多提取10个项目.

This would limit the receiving thread to pulling up to 10 items at a time.

这篇关于从线程队列中获取所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆