简体   繁体   中英

how to use multiprocessing in python right?

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:)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM