2

I am trying to use Python multiprocessing module. Here is some example code

from multiprocessing import Process 
 
def foo(): 
    print("Hello" )
 
def foo2(): 
    print("Hello again" )
 
if __name__ == '__main__':
    print('program started')
    global p1, p2
    p1 = Process(target=foo) 
    p2 = Process(target=foo2) 
    print(p1.is_alive())
    
    p1.start() 
    p2.start() 

    p1.join() 
    p2.join() 

As you can see, foo and foo2 are simple functions. I added the __name__ guard after people suggested it: Python multiprocessing processes instantly die after being started.

When I run this on my computer, I get the following output:

program started
False

The code seems to be working, so can somebody please explain?

I am using MacOS.

martineau
  • 119,623
  • 25
  • 170
  • 301
cold10
  • 130
  • 8

2 Answers2

2

Note that a process is alive from the moment its start method is called. So it is normal that is_alive returns False.

Now, if you run a program from an IDE, that might have unintended side effects. In case of problems, always run your script from the command-line first.

Roland Smith
  • 42,427
  • 3
  • 64
  • 94
-1

I FIGURED IT OUT!!

Not sure why, (can somebody help me research this?), but it seems to be IDLE's fault:

I changed IDE's to VS Code, and it worked perfectly!

cold10
  • 130
  • 8
  • 1
    Trying to run `multiprocessing` from a REPL or an IDE interpreter is usually a *bad* idea (it causes many of the same problems as not using the `__name__ == '__main__'` guard does, plus a whole bunch of new problems that are only semi-predictable), but the problem you're experiencing is almost certainly because you check `is_alive` before actually launching (calling `start` on) the `Process`. – ShadowRanger Jun 02 '22 at 23:25
  • IIRC, IDLE redirects STDOUT, so the child processes may be `print`ing to a different (invisible) console. Other IDE's have found various solutions to address this problem, but running the file directly from a terminal (without an IDE) should always work as expected. I use Spyder, and over time it has gotten better at handling stdout from multiprocessing, but that wasn't always the case. – Aaron Jun 03 '22 at 15:42