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)
1条答案
按热度按时间z9smfwbn1#
过早调用了主保护
if __name__ == '__main__':
。所以类似这样的事情是可行的:
结果是:
链接到文档:https://docs.python.org/3/library/multiprocessing.html