python-3.x 多处理属性错误:无法在〈模块“__mp_main__”上获取属性“do_something”

atmip9wb  于 2023-02-06  发布在  Python
关注(0)|答案(1)|浏览(201)
AttributeError: Can't get attribute 'do_something' on <module '__mp_main__' from 'x.py'>

当我运行我的代码时,我在终端中得到了这个错误消息。我尝试了一切,我在谷歌上搜索,并在AI答案生成网站上询问,它仍然不工作。
这是我的代码:

import multiprocessing
import time

if __name__ == '__main__':
    start = time.perf_counter()

    def do_something():
        print('Sleeping 1 second...')
        time.sleep(1)
        print('Done sleeping...')

    p1 = multiprocessing.Process(target=do_something)
    p2 = multiprocessing.Process(target=do_something)

    p1.start()
    p2.start()

    # Call join() to wait for processes to finish running
    p1.join()
    p2.join()

    finish = time.perf_counter()

    print(f'Finished in {round(finish-start, 2)} second(s)')

代码应该打印:

Sleeping 1 second...
Sleeping 1 second...
Done sleeping...
Done sleeping...
Finished in 1 second(s)
z9smfwbn

z9smfwbn1#

过早调用了主保护if __name__ == '__main__':
所以类似这样的事情是可行的:

import time
import multiprocessing

def do_something():
    print('Sleeping 1 second...')
    time.sleep(1)
    print('Done sleeping...')

start = time.perf_counter()

if __name__ == '__main__':
    p1 = multiprocessing.Process(target=do_something)
    p2 = multiprocessing.Process(target=do_something)

    p1.start()
    p2.start()

    # Call join() to wait for processes to finish running
    p1.join()
    p2.join()

    finish = time.perf_counter()

    print(f'Finished in {round(finish-start, 2)} second(s)')

结果是:

Sleeping 1 second...
Sleeping 1 second...
Done sleeping...
Done sleeping...
Finished in 2.6 second(s)

链接到文档:https://docs.python.org/3/library/multiprocessing.html

相关问题