问题
import time
from multiprocessing import Process
start = time.perf_counter()
def sleep():
print('Sleeping 1 second(s)...')
time.sleep(1)
return 'Done Sleeping...'
p1 = Process(target = sleep)
p2 = Process(target = sleep)
p1.start()
p2.start()
p1.join()
p2.join()
finish = time.perf_counter()
print(f'Finished in {round(finish-start, 2)} second(s)')
output:
Finished in 0.17 second(s)
I tried to use multiprocessing, but when I run the code it`s over in 0.17~ seconds and not 1 as it supposed to be, it's not sets off the function at all...
If I will put brackets like this :
p1 = Process(target = sleep())
p2 = Process(target = sleep())
output:
Sleeping 1 second(s)...
Sleeping 1 second(s)...
Finished in 2.35 second(s)
windows 10. python 3.7.4 thank you:)
回答1:
I have solved the problem, in order to make your code work you should add if __name__ == '__main__'
. Both of your new processes need to get access to your def sleep() in order to do it you must either separate "executable" part of your code by __name__ == "__main__"
or put def sleep() in another file and export it from there from filename import sleep
import time
from multiprocessing import Process
start = time.perf_counter()
def sleep():
print('Sleeping 1 second(s)...')
time.sleep(1)
return 'Done Sleeping...'
if __name__ == "__main__":
p1 = Process(target = sleep)
p2 = Process(target = sleep)
p1.start()
p2.start()
p1.join()
p2.join()
finish = time.perf_counter()
print(f'Finished in {round(finish-start, 2)} second(s)')
Hope the answer is useful for you.
Site form book "The Python 3 Standard Libaray by Example" by Doug Hellmann:
One difference between the threading and multiprocessing examples is the extra protection for
__main__
included in the multiprocessing examples. Due to the way the new processes are started, the child process needs to be able to import the script containing the target function. Wrapping the main part of the application in a check for__main__
ensures that it does not run recursively in each child as the module is imported. Another approach is to import the target function from a separate script. For example, multiprocessing_import_main.py uses a worker function defined in a second module.
来源:https://stackoverflow.com/questions/58414112/how-to-use-multiprocessing-in-python-right