1

I have the below python code. When I execute the code, it always displays only "End of the program!". But the print statement coded in both the definitions are not printed. is it because of multiprocessing.Process ?

Note: I am running this code in my personal laptop(tried in both Jupyter notebook as well as Spyder)

import multiprocessing 
  
def print_cube(num): 
    aa1 = num * num * num
    print("Cube: ",  aa1) 
  
def print_square(num): 
    bb1 = num * num
    print("Square: ", bb1) 
  
def main(): 
    # creating processes 
    p1 = multiprocessing.Process(target=print_square, args=(10, )) 
    p2 = multiprocessing.Process(target=print_cube, args=(10, )) 
  
    # starting process 1 
    p1.start() 

    # starting process 2 
    p2.start() 
    
    # Assumed both processes are finished 
    print("End of the program!") 

main()  
1
  • Did you mean: p1.join(); p2.join(); print("End of the program!") ? Commented Jan 31, 2021 at 17:58

1 Answer 1

5

You call start, but never call join. This means that your program starts both processes but does not wait for them to finish (so they don't have anywhere to output to). In other words, your program exits before either child process/function have a chance to finish execution.

Add

p1.join()
p2.join()
# Assumed both processes are finished
print("End of the program!")

Then the output is

Cube:  1000
Square:  100
End of the program!
Sign up to request clarification or add additional context in comments.

3 Comments

this is shown several times in the documentation as well, would be worth reading op: docs.python.org/3/library/multiprocessing.html
I have also tried adding join() statement but there is change in the output. print inside function is not coming. (Tried in both Jupyter and Spyder). Not sure exact reason p1.join() p2.join()
@LakshanthC Check yourself. This is working on Jupyter.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.