到目前为止,每当我需要使用multiprocessing
时,我都通过手动创建“进程池”并与所有子进程共享工作队列的方式来实现。
例如:
from multiprocessing import Process, Queue
class MyClass:
def __init__(self, num_processes):
self._log = logging.getLogger()
self.process_list = []
self.work_queue = Queue()
for i in range(num_processes):
p_name = 'CPU_%02d' % (i+1)
self._log.info('Initializing process %s', p_name)
p = Process(target = do_stuff,
args = (self.work_queue, 'arg1'),
name = p_name)
这样我就可以向队列中添加内容,由子进程消费。然后我可以通过检查 Queue.qsize()
来监视处理的进度:
while True:
qsize = self.work_queue.qsize()
if qsize == 0:
self._log.info('Processing finished')
break
else:
self._log.info('%d simulations still need to be calculated', qsize)
现在我想到可以使用multiprocessing.Pool
来简化这段代码。
我不知道如何监控还剩下多少工作没有完成。
看下面的例子:
from multiprocessing import Pool
class MyClass:
def __init__(self, num_processes):
self.process_pool = Pool(num_processes)
# ...
result_list = []
for i in range(1000):
result = self.process_pool.apply_async(do_stuff, ('arg1',))
result_list.append(result)
# ---> here: how do I monitor the Pool's processing progress?
# ...?
有什么想法吗?