DEV Community

pr-space
pr-space

Posted on

Doubt: multiprocessing basic example

Issue: Multiprocessing basic example running in sequential order rather than parallel in jupyter notebook

Question: Use multiprocessing to create three separate processes. Make each one wait a random number of seconds between one and five, print the current time, and then exit.

# 6) Use multiprocessing to create three separate processes. Make each one wait a random number 
# of seconds between one and five, print the current time, and then exit. 
import multiprocessing,time,datetime
import zoo

# from zoo
# def process1():
#     t1 = random.randint(1,5)
#     print("Waiting for "+str(t1)+" seconds")
#     time.sleep(t1)
#     print(datetime.datetime.now())


start = time.time()
process1 = zoo.process1()
process2 = zoo.process1()
process3 = zoo.process1()

print(datetime.datetime.now())
if __name__=="__main__":



    p1 = multiprocessing.Process(target=process1)
    p2 = multiprocessing.Process(target=process2)
    p3 = multiprocessing.Process(target=process3)

    p1.start()
    p2.start()
    p3.start()

    p1.join()
    p2.join()
    p3.join()

end = time.time()


print("It takes " +str(end-start)+" seconds")

Enter fullscreen mode Exit fullscreen mode

Top comments (0)