首页 > 解决方案 > 如何使用 ProcessPool 在进程之间有效地共享字典和列表

问题描述

让我们考虑以下示例:

from pathos.pools import ProcessPool

class A:
    def run(self, arg: int):

        my_list = list(...)
        my_dict = dict(...)

        def __run_parallel(arg: int):
            local_variable = 42

            # some code and read access...

            read_only1 = my_list[...]
            read_only2 = dict[...]


            # some code and write access...

            my_list.append(arg)
            my_dict[arg] = local_variable

        ProcessPool(4).map(__run_parallel, range(1000))

由于它似乎list也不dict是线程安全的,因此我正在寻找一种方法来有效地将对这些变量的访问共享给池中的所有进程。

到目前为止,我已经尝试将my_listmy_dict作为附加参数传递给__run_parallelusing pa.helpers.mp.Manager。然而,即使它有效,它也非常慢(因为它显然是为分布式系统构建的)。

由于我现在在一个试错会话中工作了多个晚上,我想问一下是否有人知道如何有效地使用 shareddictlistinside __run_parallelusing pathos

标签: python-3.xpathos

解决方案


正如@Mike McKerns 所建议的那样,将listdict变量都转换为没有pathos.helpers.mp.Array中间体带来了所需的性能提升。pa.helpers.mp.Manager


推荐阅读