到目前为止,无论何时我需要使用multiprocessing
,我都通过手动创建“进程池”并共享包含所有子进程的工作队列来完成此操作。如何获得由Python多处理池完成的“工作”数量?
例如:
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?
# ...?
任何想法?