【发布时间】: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