2

我正在编写一个程序来multiprocessing.Queue并行处理多个进程。我越深入到编排部分,我理解的就越少。

我想要实现的是启动几个流程并确保所有流程都已完成,然后再继续进行。这听起来像是一份工作.join()

我最终测试了以下演示脚本(在 Linux 上运行):

import multiprocessing
import time

def myproc():
    print("hello from {proc}".format(proc=multiprocessing.current_process()))
    time.sleep(5)

allproc = []
for _ in range(3):
    p = multiprocessing.Process(target=myproc)
    allproc.append(p)
    p.start()

print("all processes started")

for p in allproc:
    print("joining {proc}".format(proc=p))
    p.join()

print("the end")

我期望该功能启动 3 次,立即打印“hello”消息,然后休眠。一旦他们都完成睡眠,最后的消息(“结束”)就会被打印出来。

我实际得到的是:

hello from <Process(Process-1, started)>
hello from <Process(Process-2, started)>
all processes started
joining <Process(Process-1, started)>
hello from <Process(Process-3, started)>
joining <Process(Process-2, stopped)>
joining <Process(Process-3, stopped)>
the end

运行脚本时,它会在第三个“hello”和第二个“joining”之间等待。

我应该如何设计多处理代码,以便实现预期的编排,如上所述?

4

1 回答 1

0

如果您想要的是主线程等待所有子进程完成,print("the end")那么您的代码是正确的,根据我上面发布的解释。如果你print len(multiprocessing.active_children())在最后一行代码之前放置一个右边,你会看到它等于 0。

于 2014-12-05T20:33:04.673 回答