from multiprocessing import Pool, Manager
def task(args):
k, v, sharedDict, lock = args
with lock:
if k not in sharedDict:
sharedDict[k] = {}
sharedDict[k]['current'] = v
print(f"sharedDict[k]['current'] = {sharedDict[k]['current']}")
def main():
manager = Manager()
lock = manager.Lock()
dic = manager.dict()
pool = Pool(processes=2)
tasks = [('a', {'A': 1}, dic, lock), ('b', {'B': 2}, dic, lock), ('c', {'C': 3}, dic, lock), ('d', {'D': 4}, dic, lock)]
pool.map(task, tasks)
pool.close()
pool.join()
if __name__ == '__main__':
main()
When I run the code above, this line throws an error:print(f"sharedDict[k]['current'] ={sharedDict[k]['current']}"),KeyError: 'current', even though I've clearly added the value to the dictionary. I hope someone can help me.
From Python docs1,
sharedDict[k]is non proxy nested object in insharedDict. Its changes won't be propagated because the proxy has no way of knowing when the values contained within are modified.The work around is to create a temporary local dict.
The line
shared_dict[k] = inner_dictwill call the__setitem__on thesharedDictforcing it to update.Credit to @ken