如何访问存储在 multiprocessing.Manager 列表中的 类?

How to access classes stored in a multiprocessing.Manager list?

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

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 模块正确存储具有 class 实例的可迭代对象?

此问题与

重复

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

Note Modifications to mutable values or items in dict and list proxies will not be propagated through the manager, because the proxy has no way of knowing when its values or items are modified. To modify such an item, you can re-assign the modified object to the container proxy:

   # 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)