3

我想了解在Python多处理,我写了下面的程序:process join()如何工作?

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()方法来等待每个进程在继续执行程序之前终止。这是否意味着在两个过程执行完功能后,最后的打印语句应该在程序结束时打印? 但我的输出是:

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 

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

+3

会发生什么,如果你'进口sys',并把'sys.stdout.flush()'最终打印过吗? –

+0

@DavisYoshida,如果我使用flush(),则输出如我所料。我仍然不明白发生了什么事。 –

+0

如果我理解正确,输出被缓冲,但进程正在按照我预期的顺序执行函数。 –

回答

3

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

之所以被称为join是加盟流程集成到一个一个。 enter image description here