1

The Manager().dict() seems to work fine when the value is just a value but not when the value is a list. Is there a way to share a list between processes using a Manager()?

from multiprocessing import Process, Manager

def add(c):
    for i in range(1000):
        c['a'][0] += 1
        c['a'][1] += 2

d = Manager().dict()
d['a'] = [0,0]

p = Process(target=add, args=(d,))
p.start()
p.join()

print(d)

Output:

{1: [0, 0]}

Solved thanks @Dale Song

It seems you must do it somewhat indirectly... assign values to a temporary list and then assign the temporary list to the dictionary, weird.

from multiprocessing import Process, Array, Manager

def test(dict,m,val):
    for i in range(1000):
        m[0] +=1
        m[1] +=2
        dict[val] = m

if __name__ == '__main__':
    d = Manager().dict()
    l = [0,0]
    d['a'] = l
    p = Process(target=test, args=(d,l,'a'))
    p.start()
    p.join()
    print(d)

Output:

{'a': [1000, 2000]}

Another (much faster) way:

Using shared memory and multiprocessing.Array()

from multiprocessing import Process, Manager,Array

d = {}
d['a'] = Array('i', [0,0])


def add_array(c,val):
    for i in range(1000):
        c[val][0] +=1
        c[val][1] +=2

p = Process(target=add_array, args=(d,'a', ))
p.start()
p.join()

print([d['a'][0],d['a'][1]])

Output:

[1000, 2000]

https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Array https://docs.python.org/2/library/array.html #typecodes

Nitro
  • 1,263
  • 4
  • 16
  • 37

0 Answers0