简体   繁体   中英

Multiprocessing process does not run

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM