Home > Net >  Multiprocessing process does not run
Multiprocessing process does not run

Time:11-29

I have been trying to run a very simple multiprocessing program (script below). However, the output I am getting is simply: "Finished". Neither process or function produces any output. How do I ensure that they actually do run and I get an output that looks something like "Function 1" "Function 2" "Finished"?

Apologies if this is a duplicate question and any help would be greatly appreciated.

import multiprocessing

def func(n):
    print('Function',n)

p1 = multiprocessing.Process(target=func, args=(1, ))
p2 = multiprocessing.Process(target=func, args=(2, ))

p1.start()
p2.start()

p1.join()
p2.join()

print("Finished")

Computer info: Python version 3.8.8, macOS 12.0.1, Apple M1 chip

CodePudding user response:

Try adding __name__ == '__main__' to your code to make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects.

def func(n):
    print('Function',n)

if __name__ == '__main__':
    p1 = multiprocessing.Process(target=func, args=(1, ))
    p2 = multiprocessing.Process(target=func, args=(2, ))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    print("Finished")

source: Python docs

  • Related