进程join()如何工作?

时间:2016-02-08 17:48:25

标签: python process multiprocessing python-multiprocessing multiprocess

我试图理解Python中的多处理,我编写了以下程序:

from multiprocessing import Process

numOfLoops = 10

#function for each process
def func():
    a = float(0.0)
    for i in xrange(0, numOfLoops):
        a += 0.5
        print a 

processes = []
numOfProcesses = 2
#create the processes
for i in xrange(0, numOfProcesses):
    processes.append(Process(target=func))

for process in processes:
    process.start() #Start the processes
for process in processes:
    process.join()  #wait for each process to terminate  

print "shouldn't this statement be printed at the end??"

我创建了两个执行函数func()的进程。在继续执行程序之前,我使用join()方法等待每个进程终止。这是否意味着在两个进程执行其功能后,应在程序结束时打印最后一个print语句? 但我的输出是:

shouldn't this statement be printed at the end??
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
10
10

这不是我的预期。你能解释一下发生了什么吗?

1 个答案:

答案 0 :(得分:3)

这非常简单,它只是等待每个正在运行的进程完成,当发生这种情况时,它会返回。

称为join的原因是将流程加入到单个流程中。 enter image description here