确定 Python JoinableQueue 中有多少项
Determine how many items are in Python JoinableQueue
我正在使用 Python multiprocessing.JoinableQueue
class 并且我试图对队列施加大小限制。如果队列已满达到此限制,循环将休眠并在队列中的 space 空闲时尝试重新添加任务,但我似乎无法找到一种可靠的方法来跟踪队列大小.
我正在考虑使用这样的逻辑,结果发现我期望的 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
?不过,这似乎不是最佳选择。
任何人都将不胜感激:)
JoinableQueue
应该有一个 .full()
方法,你应该能够使用它来确定队列是否有新项目的 space。使用 full()
而不是 qsize()
意味着您可以避免单独跟踪队列的最大大小。
但是,我会避免使用它,因为它与 .qsize()
一样不可靠。队列在读取时可能正在修改中,因此无论如何您都必须处理异常情况。在带有睡眠的循环中使用 try....except
可能是实现您想尝试的最清晰、最安全和最实用的方法。
将它包装在辅助函数中可能会使代码更简单(您必须修改它以处理 func
的参数,或者在将调用传递给 try_until()
.
def try_until(func, max_tries, sleep_time):
for _ in range(0,max_tries):
try:
return func()
except:
sleep(sleep_time)
raise WellNamedException()
我正在使用 Python multiprocessing.JoinableQueue
class 并且我试图对队列施加大小限制。如果队列已满达到此限制,循环将休眠并在队列中的 space 空闲时尝试重新添加任务,但我似乎无法找到一种可靠的方法来跟踪队列大小.
我正在考虑使用这样的逻辑,结果发现我期望的 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
?不过,这似乎不是最佳选择。
任何人都将不胜感激:)
JoinableQueue
应该有一个 .full()
方法,你应该能够使用它来确定队列是否有新项目的 space。使用 full()
而不是 qsize()
意味着您可以避免单独跟踪队列的最大大小。
但是,我会避免使用它,因为它与 .qsize()
一样不可靠。队列在读取时可能正在修改中,因此无论如何您都必须处理异常情况。在带有睡眠的循环中使用 try....except
可能是实现您想尝试的最清晰、最安全和最实用的方法。
将它包装在辅助函数中可能会使代码更简单(您必须修改它以处理 func
的参数,或者在将调用传递给 try_until()
.
def try_until(func, max_tries, sleep_time):
for _ in range(0,max_tries):
try:
return func()
except:
sleep(sleep_time)
raise WellNamedException()