繁体   English   中英

确定Python JoinableQueue中有多少个项目

[英]Determine how many items are in Python JoinableQueue

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

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

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循环内try / except / sleep 不过,这似乎不是最佳选择。

任何将不胜感激:)

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

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

将其包装在辅助函数中可能会使代码更容易(您必须对其进行修改以处理func参数,或者将调用传递给try_until()之前,将其包装在无参数的lambda中。

def try_until(func, max_tries, sleep_time):
    for _ in range(0,max_tries):
        try:
            return func()
        except:
            sleep(sleep_time)
    raise WellNamedException()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM