我想在共享内存中使用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]
Run Code Online (Sandbox Code Playgroud)
这会产生如下输出:
Originally, the first two elements of arr = …Run Code Online (Sandbox Code Playgroud) 有没有一种很好的方法可以在不使用磁盘的情况下在两个python子进程之间传递大量数据?这是我希望完成的动画示例:
import sys, subprocess, numpy
cmdString = """
import sys, numpy
done = False
while not done:
cmd = raw_input()
if cmd == 'done':
done = True
elif cmd == 'data':
##Fake data. In real life, get data from hardware.
data = numpy.zeros(1000000, dtype=numpy.uint8)
data.dump('data.pkl')
sys.stdout.write('data.pkl' + '\\n')
sys.stdout.flush()"""
proc = subprocess.Popen( #python vs. pythonw on Windows?
[sys.executable, '-c %s'%cmdString],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
for i in range(3):
proc.stdin.write('data\n')
print proc.stdout.readline().rstrip()
a = numpy.load('data.pkl')
print a.shape
proc.stdin.write('done\n')
Run Code Online (Sandbox Code Playgroud)
这将创建一个子进程,该子进程生成numpy数组并将数组保存到磁盘.然后父进程从磁盘加载数组.有用!
问题是,我们的硬件可以生成比磁盘可读/写快10倍的数据.有没有办法将数据从一个python进程传输到另一个纯内存中,甚至可能没有复制数据?我可以做一些像传递参考的东西吗?
我第一次尝试纯粹在内存中传输数据是非常糟糕的:
import …Run Code Online (Sandbox Code Playgroud) 我有一个函数foo,它将一个指向内存的指针作为参数,并且对该内存进行写入和读取:
cdef void foo (double *data):
data[some_index_int] = some_value_double
do_something_dependent_on (data)
Run Code Online (Sandbox Code Playgroud)
我data这样分配:
cdef int N = some_int
cdef double *data = <double*> malloc (N * sizeof (double))
cdef int i
for i in cython.parallel.prange (N, nogil=True):
foo (data)
readout (data)
Run Code Online (Sandbox Code Playgroud)
我现在的问题是:不同的线程如何对待这个?我的猜测是指向的内存data将由所有线程共享,并在函数内部"同时"读取或写入foo.这会弄乱所有结果,因为人们不能依赖先前设定的数据值(内部foo)?我的猜测是正确的还是在cython编译器中实现了一些神奇的安全带?
非常感谢你提前.
python malloc parallel-processing cython python-multithreading