多处理Python 3 - 检查个别流程已结束

时间:2015-11-15 20:42:22

标签: python multithreading multiprocessing

我想要实现的是多个进程在同一时间运行,一旦完成继续我的程序或调用不同的功能。目前代码输出以下内容:

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

1 个答案:

答案 0 :(得分:0)

将你的print "terminated"?移到if-elif之后的start-function中。

在启动所有进程之前,主进程无法开始检测终止。因此,您永远不会看到"terminated"与计数器交错。