Python 使用队列进行多处理

Python multiprocessing with Queue

我想在 python 中使用多处理。 我的代码就像 BFS。它将任务存储在队列中,一个一个的拉出来执行。如果在执行过程中创建了新任务,则将其存储在队列中。并重复此操作直到队列为空。但是我想在这里使用多处理

这是我的代码,

def task(queue):
  results = do_task(queue.get())
  for r in results:
    queue.put(r)

pool = mp.Pool(3)
queue = mp.Manager().Queue()

init_queue(queue) #queue.put(...)
while queue.qsize() > 0:
  pool.apply_async(task, queue)
  time.sleep(0.1)

当我运行这段代码时,while循环在任务完成前退出,所以我需要使用time.sleep(..)。但是使用睡眠功能效率不高。并且不能保证任务的运行时间永远比睡眠时间短..

那么,有没有办法检查池中的进程是否在工作?

喜欢:

while queue.qsize() > 0:
  pool.apply_async(task, queue)
  time.sleep(0.1)

while queue.qsize() > 0 and check_func():
  pool.apply_async(task, queue)

谢谢!

apply_async 方法 return 是一个 AsyncResult 对象,您可以使用它来轮询结果。

这是来自 docs 的示例:

# evaluate "f(20)" asynchronously
res = pool.apply_async(f, (20,))      # start the task
print(res.get(timeout=1))             # wait at most 1 sec for the task to finish

您还可以使用该对象的 ready() 来检查调用是否已完成,而无需获取 return 值:

res.ready() # True if the call completed