简体   繁体   中英

multiprocessing.Manager() communication with main programm didn't work

Why didn't work this Code? I tried to make a Process with multiprocessing who worked in an while 1 loop. I want these Processes to have some shared memory with my main process to comunicate together. This is my Demo-Code for testing the Manager:

import multiprocessing
import time

def f(ls,lso, ):
    print "input ls:"
    print ls
    print "input lso:"
    print lso

    ls[0] += 1
    ls[1][0] += 1
    ls_2 = ls[2]
    print ls_2
    ls_2[0] += 1
    print ls_2
    ls[2] = ls_2
    print "output ls:"
    print ls
    tmp = []
    tmp.append([1, 2, 3])
    tmp.append([5, 6, 7])
    lso = tmp
    print "output lso:"
    print lso


if __name__ == '__main__':
    manager = multiprocessing.Manager()
    #ls = manager.list([1, [1], [1]])
    ls = manager.list()
    lso = manager.list()
    lso = [[0, 0, 0], [0, 0, 0]]
    tmp = []
    tmp.append(1)
    tmp.append([1])
    tmp.append([1])
    ls = tmp

    print 'before', ls, lso
    p = multiprocessing.Process(target=f, args=(ls, lso, ))
    p.start()
    p.join()
    print 'after', ls, lso

The output is:

before [1, [1], [1]] [[0, 0, 0], [0, 0, 0]]
after [1, [1], [1]] [[0, 0, 0], [0, 0, 0]]

Once a Manager.list object is created, you must set the data inside the object, as opposed to overriding it. If you sprinkle print type(lso) before and after the lso=(value) lines you'll see what I mean.

In the following code one Manager.list object is given a value at creation time: ie: myvar = list([1,2,3]) . The second is created, then data is copied into it: myvar = list(); myvar[:] = [2,3,4] myvar = list(); myvar[:] = [2,3,4]

Have fun!

source

import multiprocessing
import time

def f(ls,lso, ):
    print "input ls:"
    print ls
    print "input lso:"
    print lso

    ls[0] += 1
    ls[1][0] += 1
    ls_2 = ls[2]
    print ls_2
    ls_2[0] += 1
    print ls_2
    ls[2] = ls_2
    print "output ls:"
    print ls
    tmp = []
    tmp.append([1, 2, 3])
    tmp.append([5, 6, 7])
    lso = tmp
    print "output lso:"
    print lso


if __name__ == '__main__':
    manager = multiprocessing.Manager()
    #ls = manager.list([1, [1], [1]])
    ls = manager.list()
    lso = manager.list(
        [[0, 0, 0], [0, 0, 0]]
        )
    tmp = []
    tmp.append(1)
    tmp.append([1])
    tmp.append([1])
    ls[:] = tmp

    print 'before', ls, lso
    p = multiprocessing.Process(target=f, args=(ls, lso, ))
    p.start()
    p.join()
    print 'after', ls, lso

output

before [1, [1], [1]] [[0, 0, 0], [0, 0, 0]]
input ls:
[1, [1], [1]]
input lso:
[[0, 0, 0], [0, 0, 0]]
[1]
[2]
output ls:
[2, [1], [2]]
output lso:
[[1, 2, 3], [5, 6, 7]]
after [2, [1], [2]] [[0, 0, 0], [0, 0, 0]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM