I am unable to update the global dict in python in multiprocessing, the output is {}. What could I do wrong in the code? I intend to print out the updated dict fruits.
import multiprocessing as mp
import time
fruits ={}
def work():
global fruits
fruits["Apple"]="{'color':'Red','origin':'Germany'}"
if __name__ == "__main__":
p = mp.Process(target=work)
p.start()
time.sleep(2)
print(fruits)
CodePudding user response:
When work
runs, it is executing in its own address space and global variable fruits
that it sees is not the same global variable fruits
that the main process sees. The simplest solution is to pass to work
a managed dictionary that is sharable across processes. See the documentation.
You should also not rely on using a timer in your main process to ensure that the dictionary has been updated. Instead, call method join
on the multiprocessing.Process
instances. This will cause the main process to block until the subprocess has completed:
import multiprocessing as mp
def work(fruits):
fruits["Apple"]="{'color': 'Red', 'origin':'Germany'}"
if __name__ == "__main__":
with mp.Manager() as manager:
fruits = manager.dict()
p = mp.Process(target=work, args=(fruits,))
p.start()
p.join()
print(fruits)
Prints:
{'Apple': "{'color': 'Red', 'origin':'Germany'}"}