In the below code in function one I try to add 1 with the len(test.a) and append it to test.a it actually happen but when the program exits the function the test goes back to how it was earlier what I expect is when I print(a1.a) I would like to get [1,2,3] but I am getting [1,2]
import multiprocessing
class abc():
def __init__(self):
self.a=[1,2]
self.b=[1,2,3]
def one(test):
a=len(test.a)+1
test.a.append(a)
print('test.a==',test.a)
return test
if __name__ == '__main__':
with multiprocessing.Manager() as manager:
a1=abc()
a2=abc()
b1 = manager.list([a1])
b2 = manager.list([a2])
# print('type(a1)==', type(a1[0]))
p1 = multiprocessing.Process(target=one, args=[b1[0]])
p2 = multiprocessing.Process(target=one, args=[b2[0]])
p1.start()
p2.start()
p1.join()
p2.join()
print(a1.a)
output is:
test.a== [1, 2, 3]
test.a== [1, 2, 3]
[1, 2]
From the documentation:
If standard (non-proxy) list or dict objects are contained in a referent, modifications to those mutable values will not be propagated through the manager because the proxy has no way of knowing when the values contained within are modified. However, storing a value in a container proxy (which triggers a setitem on the proxy object) does propagate through the manager and so to effectively modify such an item, one could re-assign the modified value to the container proxy:
When you create the managed lists b1
and b2
, the manager keeps track of changes to these lists only. You can append elements to the lists, delete them, assign them. But the manager does not keep track of the elements of the list. If you modify them directly, the change does not get propogated.