Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does multiprocessing work like this normally?

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading