我有代码创建6个进程并通过管道将对象传递给父进程,在这种情况下,表达式2 ** 320000的值是在父进程中计算的,而不是在子进程中计算的。
如何在子进程中计算它,然后将结果传递给父进程?
from multiprocessing import Process, Pipe
def child(pipe, no):
for i in range(5):
#str(2 ** 320000) # It works this way
pipe.send([no, i, 2 ** 320000])
pipe.send('done')
pipe.close()
print('child %s close pipe' % no)
def parent():
procs = 6
pipes = []
for i in range(procs):
parent_pipe, child_pipe = Pipe()
process = Process(target=child, args=(child_pipe, i))
pipes.append((parent_pipe, child_pipe))
process.start()
exit_flag = [False] * procs
while False in exit_flag:
for pipe in pipes:
index = pipes.index(pipe)
if exit_flag[index]:
continue
data = pipe[0].recv()
if data == 'done':
exit_flag[index] = True
continue
print('parent got: %s' % data)
print('parent exiting...')
if __name__ == '__main__':
parent()
答案 0 :(得分:0)
您可以使用6名工作人员:
from multiprocessing import Pool
def child(no):
print('Child {0}'.format(no))
return 2 ** 320000
if __name__ == '__main__':
p = Pool(6)
results = p.map(child, list(range(5)))
print(results)
map
方法类似于内置的map
函数:它将函数应用于值列表(此处有5个值)。