使用 `pathos.pools.ProcessPool` 锁定的规范方法是什么?

What is the canonical way to use locking with `pathos.pools.ProcessPool`?

让我们考虑以下示例:

from pathos.pools import ProcessPool

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

        shared_variable = 100
        
        def __run_parallel(arg: int):
            local_variable = 0

            # ...

            if local_variable > shared_variable:
              shared_variable = local_variable

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

很明显,当使用四个进程时,if local_variable > shared_variable:shared_variable = local_variable 中存在数据竞争。

因此,我想在 if 块周围引入一个锁定机制,所以我尝试了以下操作:

from pathos.pools import ProcessPool
from multiprocessing import Lock

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

        lock = Lock()
        shared_variable = 100
        
        def __run_parallel(arg: int):
            local_variable = 0

            # ...

            lock.acquire()
            if local_variable > shared_variable:
              shared_variable = local_variable
            lock.release()

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

但是,我收到错误 RuntimeError: Lock objects should only be shared between processes through inheritance

multiprocessing 库中,似乎实现所需互斥的规范方法是使用 Manager 对象。

但是,如何在 pathos 中惯用地做到这一点?

pathos 利用 multiprocess,它与 multiprocessing 具有相同的界面,但使用 dill。您可以通过以下任一方式访问它。

>>> import pathos as pa
>>> import multiprocess as mp
>>> mp.Manager is pa.helpers.mp.Manager
True