I am trying to understand the multiprocessing in Python and trying to replicate the results of the below code(taken from Corey Schafer youtube video). The code is running but the multiprocessing module is not working. I am using windows 10 and python version 3.8.5 and my laptop has 8 cores.
import time
import multiprocessing
import workers4
tic=time.time()
processes=[]
if __name__ == '__main__':
for _ in range(50):
p=multiprocessing.Process(target=workers4.do_something,args=[20])
p.start()
processes.append(p)
for process in processes:
process.join()
toc=time.time()
elapsed=toc-tic
print("\nFinished in ",elapsed," seconds")
The file workers4.py has the function 'do_something' which makes the code sleep for some specific time value as passed through the argument.
def do_something(seconds):
print(f "Sleeping {seconds}second(s)...")
time.sleep(seconds)
print("Done sleeping...")
On running the above code, it shows only
Finished in 0.8727371692657471
seconds
and the below statements in do_something
function in the workers.py
file are not printed at all not even once.
print(f "Sleeping {seconds}second(s)..."),
print("Done sleeping...")
It seems that the do_something function is not getting executed as with a sleep time of 20sec for every process , how can the code execute in 0.8727 secs. Also there are 50 processes in the above code as in the for loop. Can someone help what is the issue and how to rectify it ??