When using multiprocessing in Python, I hope to make a list of a class as a shared variable. The class can be seen as follows(simplified):
class testClass():
def __init__(self):
self.a = []
self.b = []
Then, I use multiprocessing to process the list of 'testClass':
from multiprocessing import Process, Manager
def testProc(a_list):
for i in range(10):
a_list[1].a.append([1])
print('a_list[1] address: in processing', a_list[1])
if __name__ == '__main__':
manager = Manager()
testList = [testClass() for i in range(4)]
a_list = manager.list(testList)
print('a_list[1] address: initial ', a_list[1])
process_0 = Process(target=testProc, args=(a_list,))
process_0.start()
process_0.join()
print('a_list[1] address: final ', a_list[1])
Then the result is :
a_list[1] address: initial <__main__.testClass object at 0x7f666c160f60>
a_list[1] address: in processing <__main__.testClass object at 0x7f666c16cf28>
a_list[1] address: in processing <__main__.testClass object at 0x7f666c16cf28>
a_list[1] address: final <__main__.testClass object at 0x7f666c160f98>
It can be seen that, the address of the element of the list can vary from place to place, which fail to act as shared variable. How can I solve this problem?