从并行运行的所有进程收集数据的最佳方法是什么?获取单个流程的返回值不是问题,而是如何聚合它们?
class Controller(object):
def get_square(self,a):
return a*a
if __name__=="__main__":
controller=Controller()
jobs=[]
for param in (10,20,30):
process=Process(target=controller.get_square,kwargs={"a":param})
jobs.append(process)
process.start()
for job in jobs:
job.join()
# printing result for all processes
答案 0 :(得分:1)
from multiprocessing import Process, Queue
def square(a, qOut):
qOut.put(a**2)
if __name__ == "__main__":
qOut = Queue()
params = (10, 20, 30)
jobs = []
for p in params:
proc = Process(target=square, kwargs={'a':p, 'qOut':qOut})
jobs.append(proc)
proc.start()
for job in jobs:
job.join()
for i in range(len(params)):
print(qOut.get())