Search code examples
pythonpython-multiprocessing

I can't start two functions at the same time, with multiprocessing Python. Why?


I just want to start 2 functions at the same time but it doesn't work, here is it my code:

from multiprocessing import Process
import time as t
def print1():
    print(1)
    t.sleep(10)

def print2():
    print(1)
    t.sleep(10)
if __name__ == '__main__':
    p1 = Process(target = print1)
    p1.start()
    p1.join()
    p2 = Process(target = print2)
    p2.start()
    p2.join()

I don't have any problesms on console but function doesn't start at the same time. What's wrong?


Solution

  • From this post on how to start all processes simultaneously in Python instead of

        p1 = Process(target = print1)
        p1.start()
        p1.join()
        p2 = Process(target = print2)
        p2.start()
        p2.join()
    

    do

        p1 = Process(target = print1)
        p2 = Process(target = print2)
        p1.start()
        p2.start()
        p1.join()
        p2.join()
    

    then to run another function after it, you can do

        p1 = Process(target = print1)
        p2 = Process(target = print2)
        p3 = Process(target = print3)
        p1.start()
        p2.start()
        p1.join()
        p2.join()
        p3.start()
        p3.join()