Does multiprocessing work like this normally?

Question:

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]

Asked By: Nikunj Vashishtha

||

Answers:

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
Answered By: tdelaney
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.