为什么没有使用此代码?我尝试使用多处理程序创建一个在1循环中工作的进程。我希望这些进程与我的主进程有一些共享内存来共同通信。这是我用于测试管理器的演示代码:
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
输出结果为:
before [1, [1], [1]] [[0, 0, 0], [0, 0, 0]]
after [1, [1], [1]] [[0, 0, 0], [0, 0, 0]]
答案 0 :(得分:0)
创建Manager.list
对象后,您必须设置对象内的数据,而不是覆盖它。如果你在print type(lso)
行之前和之后撒上lso=(value)
,你会看到我的意思。
在以下代码中,一个Manager.list对象在创建时被赋予一个值:ie:myvar = list([1,2,3])
。创建第二个,然后将数据复制到其中:myvar = list(); myvar[:] = [2,3,4]
玩得开心!
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
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]]