0
我試圖實現的是多個進程在完全相同的時間運行,一旦完成後繼續我的程序或調用不同的函數。目前,該代碼輸出如下:多進程Python 3 - 檢查個別進程已結束
2
3
1
[<Process(Process-1, started)>, <Process(Process-2, started)>, <Process(Process-
3, started)>]
Terminated
Terminated
Terminated
[Finished in 4.1s]
所以我知道該啓動功能被稱爲3倍,並同時運行,但怎麼來的處理是正確的,在最終只終止?當然輸出將是:
2
Terminated
3
Terminated
1
Terminated
如果任何人可以擺脫這一點,我將不勝感激。提前致謝。
import multiprocessing, time
def start(counter):
if(counter == 0):
time.sleep(4)
print(1)
elif(counter == 1):
time.sleep(0.2)
print(2)
elif(counter==2):
time.sleep(3)
print(3)
if __name__ == '__main__':
processes = []
for x in range(0, 3):
p = multiprocessing.Process(target=start, args=(x,))
processes.append(p)
p.start()
print(processes)
while len(processes) > 0:
for process in processes:
if not process.is_alive():
processes.remove(process)
print ("Terminated")
#Program continues once all the processes have finished
您可以使用'multiprocessing.Pool'來代替自己處理所有進程。 –