Search code examples
pythonpython-3.xmultiprocessingpython-multiprocessing

Multi-processing skip beginning


I am quite new to python and the multi-processing module. I want to know how to make the process skip the beginning so it doesn't repeat it. Any help would be appreciated :)

print("Doing something!!!")

Code:

import multiprocessing

print("Doing something!!!")

def stuff():
    print("Doing stuff")

if __name__  == '__main__':
    p1 = multiprocessing.Process(target=stuff)
    p1.start()

Output:

Doing something!!!
Doing something!!!
Doing stuff

Desired output:

Doing something!!!
Doing stuff

Solution

  • See the multiprocessing Programming Guidelines in the documentation.

    On systems that use the "spawn" or "forkserver" methods of creating processes:

    Make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process).

    Your script is being imported into every process, so it will run any global code in all processes. Just move anything global into the if __name__ == '__main__': section:

    import multiprocessing
    
    def stuff():
        print("Doing stuff")
    
    if __name__  == '__main__':
        print("Doing something!!!")
        p1 = multiprocessing.Process(target=stuff)
        p1.start()
    

    This insures the function stuff() will be imported and defined in every process, but your print will only run once in the main process.