【问题标题】:What is the canonical way to use locking with `pathos.pools.ProcessPool`?使用“pathos.pools.ProcessPool”锁定的规范方法是什么?
【发布时间】:2020-10-24 21:44:06
【问题描述】:

让我们考虑以下示例:

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 中惯用地执行此操作?

【问题讨论】:

    标签: python python-3.x pathos


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      • 2018-01-27
      • 2015-01-25
      • 1970-01-01
      相关资源
      最近更新 更多