确定Python中的项目数量JoinableQueue

时间:2015-11-18 21:34:44

标签: python queue multiprocessing

我正在使用Python multiprocessing.JoinableQueue类,我正在尝试对队列施加大小限制。如果队列已达到此限制,则循环将休眠并尝试在队列中的空间释放时重新添加任务,但我似乎找不到可靠的方法来跟踪队列大小。

我正在考虑使用这样的逻辑,只是为了找出.qsize()模块所期望的Queue函数不存在:

from multiprocessing import JoinableQueue
QUEUE_SIZE = 50
QUEUE_WAIT = 900
task_queue = JoinableQueue(QUEUE_SIZE)
....
if QUEUE_SIZE is not 0:
    # if QUEUE_SIZE is zero, there is no limit on the queue
    while True:
        # if the size of the queue equals our self-imposed limit, wait to try and add this task
        if task_queue.qsize() == QUEUE_SIZE:
            print 'task queue limit is met. task will be added when space clears'
            time.sleep(QUEUE_WAIT)
        else:
            # add the task if we can
            self.task_queue.put(path)
            print 'task queued" task="%s"' % path)
            break

    else:
        # if there's no limit just add the file_path
        self.task_queue.put(file_path)

是否有一种首选方式可以跟踪JoinableQueue中当前有多少项目,或者如果无法立即添加项目,可能是更好的方法重新尝试将项目添加到队列中?也许只是循环中的try / except / sleep?不过,这似乎不是最好的选择。

任何人都会非常感激:)

1 个答案:

答案 0 :(得分:1)

JoinableQueue应该有.full()方法,您应该可以使用该方法来确定队列是否有新项目的空间。使用full()代替qsize()意味着您可以避免必须单独跟踪队列的最大大小。

但是,我会避免使用它,因为它与.qsize()一样不可靠。在读取队列时,队列可能是中间修改,因此您无论如何都必须处理异常情况。在睡眠循环中使用try....except可能是实现您想要尝试的最清晰,最安全和最实用的方法。

将它包装在辅助函数中可能会使代码更容易(您必须修改它以处理func的参数,或者在将调用包装到no-arg lambda之前将其传递给{{1} }。

try_until()