我想在共享内存中使用一个numpy数组,用于多处理模块。困难在于像numpy数组一样使用它,而不仅仅是ctypes数组。
from multiprocessing import Process, Array
import scipy
def f(a):
a[0] = -a[0]
if __name__ == '__main__':
# Create the array
N = int(10)
unshared_arr = scipy.rand(N)
arr = Array('d', unshared_arr)
print "Originally, the first two elements of arr = %s"%(arr[:2])
# Create, start, and finish the child processes
p = Process(target=f, args=(arr,))
p.start()
p.join()
# Printing out the changed values
print "Now, the first two elements of arr = %s"%arr[:2]
这将产生如下输出:
Originally, the first two elements of arr = [0.3518653236697369, 0.517794725524976]
Now, the first two elements of arr = [-0.3518653236697369, 0.517794725524976]
可以用ctypes方式访问数组,例如:arr[i]
有意义。然而,它不是一个numpy数组,我不能执行-1*arr
或arr.sum()
等操作。我想一个解决方案是将ctypes数组转换为numpy数组。然而(除了不能使这个工作),我不相信它会被共享了。
似乎有一个标准的解决方案,什么必须是一个共同的问题。
6条答案
按热度按时间u7up0aaq1#
添加到@unutbu的(不再可用)和@亨利戈默 solr 的答案。您可以在需要时使用
shared_arr.get_lock()
来同步访问:示例
如果你不需要同步访问或者你创建了自己的锁,那么
mp.Array()
是不必要的。在这种情况下,可以使用mp.sharedctypes.RawArray
。hrirmatl2#
Array
对象有一个与之关联的get_obj()
方法,该方法返回ctypes数组,该数组表示缓冲区接口。我认为以下几点应该是可行的...运行时,打印出
a
的第一个元素,现在是10.0,显示a
和b
只是同一内存中的两个视图。为了确保它仍然是多处理器安全的,我相信你必须使用
Array
对象a
上存在的acquire
和release
方法,以及它的内置锁,以确保它的所有安全访问(尽管我不是多处理器模块的Maven)。pcww981p3#
虽然已经给出的答案是好的,但如果满足两个条件,这个问题有一个更容易的解决方案:
1.您使用的是POSIX兼容操作系统(例如,Linux、Mac OSX);和
1.您的子进程需要对共享数组进行只读访问。
在这种情况下,您不需要显式地使变量共享,因为子进程将使用fork创建。分叉的子节点自动共享父节点的内存空间。在Python多处理的上下文中,这意味着它共享所有 * 模块级 * 变量;请注意,对于显式传递给子进程或在
multiprocessing.Pool
上调用的函数的参数,这 * 不成立 *。举个简单的例子:
wgeznvg74#
我写了一个小的python模块,它使用POSIX共享内存在python解释器之间共享numpy数组。也许你会发现它很方便。
https://pypi.python.org/pypi/SharedArray
它的工作原理如下:
uidvcgyl5#
您可以使用
sharedmem
模块:https://bitbucket.org/cleemesser/numpy-sharedmem下面是你的原始代码,这次使用的是共享内存,其行为类似于NumPy数组(注意最后一个调用NumPy
sum()
函数的语句):0yg35tkg6#
在Python 3.8+中,你可以使用
multiprocessing.shared_memory
标准库模块来创建一个由共享内存支持的numpy数组。此共享内存可以由多个进程访问。下面是一个示例:运行脚本:
由于不同进程中的数组共享相同的底层内存缓冲区,因此标准警告r.e.竞争条件适用。