我希望能够在多个进程之间共享numpy数组。这里有一些可行的解决方案(链接)。但是它们都通过继承将数组传递给子进程,这对我来说不起作用,因为我必须先启动几个工作进程,而且我不知道以后会处理多少个数组。是否有任何方法可以在进程启动后创建这些数组,并通过队列将这些数组传递给进程?
顺便说一下,由于某种原因,我无法使用
顺便说一下,由于某种原因,我无法使用
multiprocessing.Manager
。multiprocessing.Manager
。以下是官方 Python 文档的示例:
>>> # In the first Python interactive shell
>>> import numpy as np
>>> a = np.array([1, 1, 2, 3, 5, 8]) # Start with an existing NumPy array
>>> from multiprocessing import shared_memory
>>> shm = shared_memory.SharedMemory(create=True, size=a.nbytes)
>>> # Now create a NumPy array backed by shared memory
>>> b = np.ndarray(a.shape, dtype=a.dtype, buffer=shm.buf)
>>> b[:] = a[:] # Copy the original data into shared memory
>>> b
array([1, 1, 2, 3, 5, 8])
>>> type(b)
<class 'numpy.ndarray'>
>>> type(a)
<class 'numpy.ndarray'>
>>> shm.name # We did not specify a name so one was chosen for us
'psm_21467_46075'
>>> # In either the same shell or a new Python shell on the same machine
>>> import numpy as np
>>> from multiprocessing import shared_memory
>>> # Attach to the existing shared memory block
>>> existing_shm = shared_memory.SharedMemory(name='psm_21467_46075')
>>> # Note that a.shape is (6,) and a.dtype is np.int64 in this example
>>> c = np.ndarray((6,), dtype=np.int64, buffer=existing_shm.buf)
>>> c
array([1, 1, 2, 3, 5, 8])
>>> c[-1] = 888
>>> c
array([ 1, 1, 2, 3, 5, 888])
>>> # Back in the first Python interactive shell, b reflects this change
>>> b
array([ 1, 1, 2, 3, 5, 888])
>>> # Clean up from within the second Python shell
>>> del c # Unnecessary; merely emphasizing the array is no longer used
>>> existing_shm.close()
>>> # Clean up from within the first Python shell
>>> del b # Unnecessary; merely emphasizing the array is no longer used
>>> shm.close()
>>> shm.unlink() # Free and release the shared memory block at the very end
对于像你这样的真实用例,你需要使用Pipe
或其他多进程通信机制传递名称shm.name
。请注意,只需在进程之间交换此小字符串即可;实际数据保留在共享内存空间中。
np.memmap
可能是一个不错的方法。数据将存储在磁盘上,但它像标准数组一样使用,并且只有“头”数据被pickle在队列中,因此非常快速。
fork
系统调用,并且子进程会继承父进程的所有程序状态,包括共享内存句柄。避免通过继承传递的示例在此处:https://dev59.com/OWkw5IYBdhLWcg3waZ74 - shaoyl85