1
我正在編寫一個程序,通過多個進程並行處理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 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 12:04:11
我的意思是「房屋」。 – 2014-12-05 20:18:34