how to use multiprocessing in python right?

牧云@^-^@ 提交于 2021-01-27 06:41:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!