我正在尝试使用
例如:
这将输出:
ThreadPool
和Queue
实现一个处理任务队列的线程池。它从一个初始任务队列开始,然后每个任务都可以将其他任务推送到任务队列中。问题是我不知道如何在阻塞队列直到队列为空并且线程池完成处理的同时,检查队列并提交任何新任务到线程池中。我不能简单地调用ThreadPool.join()
,因为我需要保持线程池打开以接受新任务。例如:
from multiprocessing.pool import ThreadPool
from Queue import Queue
from random import random
import time
import threading
queue = Queue()
pool = ThreadPool()
stdout_lock = threading.Lock()
def foobar_task():
with stdout_lock: print "task called"
if random() > .25:
with stdout_lock: print "task appended to queue"
queue.append(foobar_task)
time.sleep(1)
# set up initial queue
for n in range(5):
queue.put(foobar_task)
# run the thread pool
while not queue.empty():
task = queue.get()
pool.apply_async(task)
with stdout_lock: print "pool is closed"
pool.close()
pool.join()
这将输出:
pool is closed
task called
task appended to queue
task called
task appended to queue
task called
task appended to queue
task called
task appended to queue
task called
task appended to queue
在foobar_tasks被添加到队列之前,该代码就退出了while循环,因此这些已添加的任务从未被提交到线程池。我找不到任何方法来确定线程池是否仍有活动的工作线程。我尝试了以下方法:
while not queue.empty() or any(worker.is_alive() for worker in pool._pool):
if not queue.empty():
task = queue.get()
pool.apply_async(task)
else:
with stdout_lock: print "waiting for worker threads to complete..."
time.sleep(1)
但似乎worker.is_alive()
总是返回true,因此会进入无限循环。
有没有更好的方法?