Home > other >  Does multiprocessing work like this normally?
Does multiprocessing work like this normally?

Time:01-30

Source Code

import multiprocessing
import time


inTime = time.time()
def sleeper():
    print("Im sleeper")
    time.sleep(1)

if __name__ == "__main__":
    p1 = multiprocessing.Process(sleeper())
    p1.start()
    p1.join()
    p2 = multiprocessing.Process(sleeper())
    p2.start()
    p2.join()

    nTime = time.time()
    print(f"done in {round(nTime-inTime,2)} s")

I'm not getting it to work as expected. It must complete the process within 1s but it takes 2s queuing one function after another. I'm running it on Python 3.11.1 [64bit]

CodePudding user response:

You have three problems. First, you call sleeper() and then create a process that does nothing. Second, you join the first process before even starting the second. Third, the target subprocess function should be in the target parameter. To get things to go in parallel, you can do

import multiprocessing
import time

inTime = time.time()
def sleeper():
    print("Im sleeper")
    time.sleep(1)

if __name__ == "__main__":
    p1 = multiprocessing.Process(target=sleeper)
    p1.start()
    p2 = multiprocessing.Process(target=sleeper)
    p2.start()
    p1.join()
    p2.join()

    nTime = time.time()
    print(f"done in {round(nTime-inTime,2)} s")

Output

Im sleeper
Im sleeper
done in 1.01 s
  • Related