1

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

3
  • 1
    Depending on the OS you do not receive the stdout output of a subprocess on your console. Commented Nov 28, 2021 at 10:10
  • 2
    Multiprocessing starts new processes, are you sure it's not running and just outputting to stdout that goes to nowhere? Did you try for example creating a file in the process instead of just printing something? Commented Nov 28, 2021 at 10:10
  • 1
    Ah yes thank you! Sending the output to a file works. Is there a way to make it actually print to the console? Commented Nov 28, 2021 at 10:17

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Tried that too and got the same result.
That is strange, it worked for me on my M1 chip, but with python 3.9.2. Also worked in python 2.7
Okay I'll try updating to Python 3.9 then. Maybe that'll work

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.