在 M1 Macbook 上使用“Pool”进行多重处理会引发错误

2024-02-02

在我的 Macbook Pro(英特尔,2020)上我可以成功使用multiprocessing.Pool like:

from multiprocessing import Pool

p = Pool(8)
results = p.map(worker_function, list_of_inputs)
p.close()

但是,如果我在 Macbook Air(M1,2020)上运行相同的代码,我会一次又一次地重复出现奇怪的错误(片段如下):

RuntimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.

为了解决这个问题,我首先阅读这篇博文 https://pythonspeed.com/articles/python-multiprocessing/。作者解释了 Python 启动新线程的不同方式,例如经过fork-ing(基本上复制现有的解释器及其大部分内存),spawn- 聘请新的口译员,等等。

在官方文档中 https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods,看来 OSX 上的默认启动方法是fork。然而,我注意到,在我的 Macbook(M1,2020)上,如果我运行:

import multiprocessing

multiprocessing.get_start_method()

I get "spawn".

所以我设法解决这个问题通过明确声明我想要"fork"创建池时的start方法。

from multiprocessing import get_context

p = get_context("fork").Pool(8)
results = p.map(worker_function, list_of_inputs)
p.close()

Update

你结帐了吗ray https://docs.ray.io/en/latest/?它速度更快,并且具有更清晰的多处理 API。上面的内容很简单:

import ray
results = ray.get([worker_funtion.remote(inp) for inp in list_of_inputs])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 M1 Macbook 上使用“Pool”进行多重处理会引发错误 的相关文章

随机推荐