Can't modify global dict variable using mutliprocessing in python
Question: I try to use multiprocessing to process numpy array. But I don't know how to
return the process result back to the dict variable.

Use the comments out code can produce what I expected. But when I try to use
multiprocessing, I can't get anything for the `max_rslts`, it is an empty
dict.

The example code is:

    
    
    from __future__ import print_function
    
    from multiprocessing import Process
    import numpy as np
    
    def calc_max(a, step):
        global max_rslts
        max_rslts[step] = a[::step].max()
    
    
    if __name__ == '__main__':
        max_rslts = dict()
    
        a1 = np.arange(16).reshape(4,4)
    
    #    for i in range(1,4):
    #        calc_max(a1, i)
    #    print(max_rslts)
    
        jobs = []
        for i in range(1,4):
            p = Process(target=calc_max, args=(a1, i))
            jobs.append(p)
            p.start()
    
        for j in jobs:
            j.join()
    
        print(a1)
        print(max_rslts)
    


Answer: From the [`multiprocessing` programming
guidelines](http://docs.python.org/2/library/multiprocessing.html#programming-
guidelines):

> Avoid shared state

`global`s are not shared between processes after forking off each sub-process.
Use different means to [share state between
processes](http://docs.python.org/2/library/multiprocessing.html#sharing-
state-between-processes) instead. A [`dict`
manager](http://docs.python.org/2/library/multiprocessing.html#managers) would
work here:

    
    
    from __future__ import print_function
    
    from multiprocessing import Process, Manager
    import numpy as np
    
    
    def calc_max(a, step, max_rslts):
        max_rslts[step] = a[::step].max()
    
    
    if __name__ == '__main__':
        manager = Manager()
        max_rslts = manager.dict()
        a1 = np.arange(16).reshape(4,4)
        jobs = []
        for i in range(1,4):
            p = Process(target=calc_max, args=(a1, i, max_rslts))
            jobs.append(p)
            p.start()
    
        for j in jobs:
            j.join()
    
        print(a1)
        print(max_rslts)
    

