I have a class B
which is composed of another class A
.
In class B
I am using multiprocessing pool to call a method from class A
. This method updates a member variable of A
(which is a dict).
When I print out this member variable it doesn't seem to have been updated. Here is the code describing the issue:
import multiprocessing as mp
class A():
def __init__(self):
self.aDict = {'key': 0}
def set_lock(self, lock):
self.lock = lock
def do_work(self, item):
print("Doing work for item: {}".format(item) )
self.aDict['key'] += 1
return [1,2,3] # return some list
class B():
def __init__(self):
self.objA = A()
def run_with_mp(self):
items=['item1', 'item2']
with mp.Pool(processes=mp.cpu_count()) as pool:
result = pool.map_async(self.objA.do_work, items)
result.wait()
pool.terminate()
print(self.objA.aDict)
def run(self):
items=['item1', 'item2']
for item in items:
self.objA.do_work(item)
print(self.objA.aDict)
if __name__ == "__main__":
b = B()
b.run_with_mp() # prints {'key': 0}
b.run() # prints {'key': 2}
b.run_with_mp()
prints {'key': 0}
whole b.run()
prints {'key': 2}
. I thought the multiprocessing pool version would also do the same since the object self.objA
had scope for the full class of B
where the multiprocessing pool runs.
I think each worker of the pool sees a different version of self.objA
, which are different from the one in the main program flow. Is there a way to make all the workers update a common variable?