I have a Python script with a simple function. I would like to run this function 2 times, simultaneously and was wondering if this was possible.
script.py:
from multiprocessing import Process
import time
def func1():
time.sleep(1)
print('Finished sleeping')
t1_start = time.perf_counter()
p1 = Process(target=func1())
p1 = Process(target=func1())
t1_stop = time.perf_counter()
print("elapsed time: {} sec".format(round(t1_stop - t1_start), 1))
Given output:
Finished sleeping
Finished sleeping
elapsed time: 2 sec
Expected output:
Finished sleeping
Finished sleeping
elapsed time: 1 sec
I have also tried this:
from multiprocessing import Process
import time
def func1():
time.sleep(1)
print('Finished sleeping')
if __name__ == '__main__':
t1_start = time.perf_counter()
p1 = Process(target=func1) # note no ()
p2 = Process(target=func1) # note no ()
p1.start()
p2.start()
t1_stop = time.perf_counter()
print("elapsed time: {} sec".format(round(t1_stop - t1_start), 1))
However that gives this output:
elapsed time: 0 sec
Finished sleeping
Finished sleeping
CodePudding user response:
target=func1()
callsfunc1
and passes its return value (in this caseNone
) as the target argument forProcess
instead of passing the functionfunc1
itself.Process(...)
just creates aProcess
object. You never really spawn/execute any of the createdProcess
objects. You need to add a call to.start
. Depending on the OS (ie ifos.fork
is used to spawn the new process), this will also require us to add__main__
guard (which is a best-practice anyway regardless of the used OS).You are using
p1
twice.
Try this:
from multiprocessing import Process
import time
def func1():
time.sleep(1)
print('Finished sleeping')
if __name__ == '__main__':
t1_start = time.perf_counter()
p1 = Process(target=func1) # note no ()
p2 = Process(target=func1) # note no ()
p1.start()
p2.start()
t1_stop = time.perf_counter()
print("elapsed time: {} sec".format(round(t1_stop - t1_start), 1))
This gives the output
elapsed time: 0 sec
Finished sleepingFinished sleeping
which makes sense. If the function is executed 2 times in separated processes then the main process, the main process would not execute time.sleep(1)
at all.
However, if we add .join()
then the main process will be forced to wait for the child processes:
p1.start()
p2.start()
p1.join()
p2.join()
Now the output is the same as your required output:
Finished sleeping
Finished sleeping
elapsed time: 1 sec