我试图理解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

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

最佳答案

它非常简单,它只是等待每个正在运行的进程完成,当这种情况发生时,它返回。
之所以称为join是因为它将进程连接到单个进程中。
python - 流程join()如何工作?-LMLPHP

10-07 21:38