我正在编写一个程序,通过几个进程并行地处理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")我所期望的是函数启动三次,立即打印"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当运行脚本时,它在第三个“你好”和第二个“加入”之间等待。
如何设计多处理代码,以便实现上述预期的业务流程?
发布于 2014-12-05 20:33:04
如果您想要的是等待在print("the end")之前完成所有子进程的主线程,那么您的代码是正确的,正如我上面发布的解释所示。如果在最后一行代码前面放置一个print len(multiprocessing.active_children()),您将看到它等于0。
https://stackoverflow.com/questions/27313941
复制相似问题