3

I am trying to understand multiprocessing in Python, I wrote the following program:

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??"

I created two processes that executes function func(). I used join() method to wait for each process to terminate before proceeding with the program. Doesn't this mean that the last print statement should be printed at the end of the program after the two processes have executed their function? But my output was:

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

Which is not what I expected. Can you explain what's going on?

Rakesh Adhikesavan
  • 11,966
  • 18
  • 51
  • 76

1 Answers1

3

It is very simple, it just waits for each of the running processes to finish and when this happens, it returns.

The reason why is called join is that is joining the processes into a single one. enter image description here

sorin
  • 161,544
  • 178
  • 535
  • 806