I was trying to build a simple example of new Python SharedMemory class by amending a shared numpy array. I`ve seen a few examples on the web here:
Shared memory in multiprocessing
Is shared readonly data copied to different processes for multiprocessing?
However all of them change the shared array inside the __main__
block for some reason and then just print it. However, I would like to return a shared array from the function and reuse it later. Here is my try:
from multiprocessing import shared_memory
import numpy as np
def create_shared_array():
# instantiate array
np_array = np.ones((5, 2, 2))
# instantiate shared array
shm = shared_memory.SharedMemory(size=np_array.nbytes, create=True)
# copy data from original array into shared array
array_shared = np.ndarray(np_array.shape, dtype=np_array.dtype, buffer=shm.buf)
array_shared[:] = np_array[:]
return shm
def change_and_return(name):
existing_shm = shared_memory.SharedMemory(name=name, create=False)
array_shared = np.ndarray((5, 2, 2), dtype=np.float64, buffer=existing_shm.buf)
# change shared array
array_shared[0] = 888
return array_shared
shm = create_shared_array()
result = change_and_return(shm.name)
print(result)
For some reason this code returns "The instruction at <memory address> referenced memory at <another address>. The memory could not be read."
on my Windows machine.
However, if I just replace this
return array_shared
with this
return array_shared.copy()
Then it works just fine.
My thoughts:
Since change_and_return
does not return existing_shm
then it gets garbage collected and array_shared
is destroyed as well. However, I do make sure not to kill shm
so the reference should still exist ?
Question: why an additional copy is required and what is the right way here to avoid making an additional copy ?
UPDATE: let me be clear here - I would like to change array values in shared memory but after that I would like to use it in a non-shared fashion. Just like a regular numpy array. So the question is basically if it is possible to turn a shared array back into non-shared one without copying ?