首页 > 解决方案 > 如何访问存储在 multiprocessing.Manager 列表中的类?

问题描述

我可以访问和更改列表中类的属性,如下所示:

class TestClass:
    def __init__(self):
        self.value = 1

instances = [TestClass()]
instances[0].value = 42
print(instances[0].value)  # 42

但是,当使用 时multiprocessing.Manager,我的代码似乎没有任何效果:

from multiprocessing import Manager
with Manager() as manager:
    instances = manager.list([TestClass()])
    instances[0].value = 42
    print(instances[0].value)  # 1

如何使用模块正确存储带有类实例的可迭代对象multiprocessing

标签: pythonpython-3.xpython-multiprocessingmultiprocessing-manager

解决方案


此问题与添加值以设置包含在 Multiprocessing.Manager().list() 中的重复

正如@torek 所说,代理管理器无法将您的更改传播到底层对象,因此您必须完全替换它。

注意 对 dict 和 list 代理中的可变值或项的修改不会通过管理器传播,因为代理无法知道其值或项何时被修改。要修改此类项目,您可以将修改后的对象重新分配给容器代理:

   # create a list proxy and append a mutable object (a dictionary)
   lproxy = manager.list()
   lproxy.append({})
   # now mutate the dictionary
   d = lproxy[0]
   d['a'] = 1
   d['b'] = 2
   # at this point, the changes to d are not yet synced, but by
   # reassigning the dictionary, the proxy is notified of the change
   lproxy[0] = d

所以,这是你的解决方案:

with Manager() as manager:
    instances = manager.list([TestClass()])
    newInstance = TestClass()
    newInstance.value = 42
    instances[0] = newInstance
    print(instances[0].value)

推荐阅读