我正在Python中进行多处理实验,并试图在两个进程之间共享一个字符串数组。这是我的python代码:
from multiprocessing import Process, Array, Value import ctypes def f1(a, v): for i, l in enumerate(['a', 'b', 'c']): a[i] = l*3 v.value += 1 print "f1 : ", a[:], v.value def f2(a,v): v.value += 1 print "f2 : ", a[:], v.value if __name__ == '__main__': val = Value(ctypes.c_int, 0) arr = Array(ctypes.c_char_p, 3) print "Before :", arr[:], val.value p = Process(target=f1, args=(arr, val)) p2 = Process(target=f2, args=(arr, val)) p.start() p2.start() p.join() p2.join() print "After : ", arr[:], val.value
运行脚本时,我看到该脚本arr已正确填充,并且可在中找到,f1()但不能在中找到f2()。结果如下:
arr
f1()
f2()
% python /tmp/tests.py Before : [None, None, None] 0 f1 : ['aaa', 'bbb', 'ccc'] 1 f2 : ['\x01', '\x11', '\x01'] 2 After : ['\x01', '\x01', '\x01'] 2
我忽略了什么吗?
预先感谢您的反馈。:)
我的猜测是:
arr存储3个指针。f1()将它们分配给当前进程之外没有意义的内存地址。f2()尝试访问此时包含垃圾邮件的无意义地址。
分配对所有过程都有意义的值似乎有帮助:
from __future__ import print_function import ctypes import time from multiprocessing import Process, Array, Value values = [(s*4).encode('ascii') for s in 'abc'] def f1(a, v): for i, s in enumerate(values): a[i] = s v.value += 1 print("f1 : ", a[:], v.value) def f2(a,v): v.value += 1 print("f2 : ", a[:], v.value) def main(): val = Value(ctypes.c_int, 0) arr = Array(ctypes.c_char_p, 3) print("Before :", arr[:], val.value) p = Process(target=f1, args=(arr, val)) p2 = Process(target=f2, args=(arr, val)) p.start() p2.start() p.join() p2.join() print("After : ", arr[:], val.value) if __name__ == '__main__': main()
Before : [None, None, None] 0 f1 : ['aaaa', 'bbbb', 'cccc'] 1 f2 : ['aaaa', 'bbbb', 'cccc'] 2 After : ['aaaa', 'bbbb', 'cccc'] 2