Shared Array not shared correctly in python multiprocessing(共享数组在 python 多处理中未正确共享)
问题描述
我正在 Python 中尝试多处理,并尝试在两个进程之间共享一个字符串数组.这是我的python代码:
I am experimenting multiprocessing in Python and tried to share an Array of strings among two processes. Here is my python code :
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()
中不可用.结果如下:
When I run the script I see that arr
is correctly populated and available in f1()
but not in f2()
. Here is the result:
% python /tmp/tests.py
Before : [None, None, None] 0
f1 : ['aaa', 'bbb', 'ccc'] 1
f2 : ['x01', 'x11', 'x01'] 2
After : ['x01', 'x01', 'x01'] 2
我是否忽略了什么?
提前感谢您的反馈.:)
Thanks in advance for your feedback. :)
推荐答案
我的猜测是:
arr
存储 3 个指针.f1()
将它们分配给没有意思是在当前流程之外.f2()
尝试访问此时包含垃圾的无意义地址.
arr
stores 3 pointers.f1()
assigns them to memory addresses that have no meaning outside current process.f2()
tries to access the meaningless addresses that contain junk at this point.
分配给在所有过程中都有意义的值似乎有帮助:
Assigning to values that have meaning in all processes seems to help:
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
这篇关于共享数组在 python 多处理中未正确共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:共享数组在 python 多处理中未正确共享
基础教程推荐
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 筛选NumPy数组 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01