Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does process join() work?

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?

like image 524
Rakesh Adhikesavan Avatar asked Dec 03 '25 15:12

Rakesh Adhikesavan


1 Answers

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

like image 100
sorin Avatar answered Dec 06 '25 03:12

sorin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!