Search code examples
pythonpython-multiprocessing

Python multi processing start the script over again?


I am using multi processing in Python. The following is the demo of my code:

In function main:

from multiprocessing import Process

def __name__ == "__main__":
    print "Main program starts here."

    SOME CODE....

    process_1 = Process(target=proc1,  args = (arg1, arg2))
    process_2 = Process(target=proc2,  args = (arg3, arg4))
    
    process_1.start()
    process_2.start()
    
    process_1.join()
    process_2.join()

And in function proc1 and proc2:

def proc1(arg1, arg2):
    print "Proc1 starts from here."

    SOME CODE....

So what I expect to see as output is:

Main program starts here.

Proc1 starts from here.

Proc2 starts from here.

However, what I got is:

Main program starts here.

Main program starts here.

Main program starts here.

It seems that both the proc1 and proc2 start the main rather than the procs.

May I know what is wrong with my code?

Many thanks.


Solution

  • def __name__ == "__main__":
    

    Should be:

    if __name__ == "__main__":
    

    But if I execute your code with python 2.7 I get:

        def __name__ == "__main__":
                      ^
    SyntaxError: invalid syntax
    

    If I rename def to if:

    Main program starts here.
    proc2
    proc1
    

    So I wonder how you get your code working (you probably modified it before pasting it here)