I am trying to use the shared_memory with pool in python's multiprocessing.
In the Documentation, about shared memory, the argument buf (the memory view) is not clear to me (perhaps because I don't understand the concept of memory view - is it a pointer?).
I want to use this shared memory across different processes. Following, my example base on the documentation:
a = np.array([1, 1, 2, 3, 5, 8])
shm = shared_memory.SharedMemory(create=True, size=a.nbytes)
# Do I need to create the existing_shm or I can keep using shm?
existing_shm = shared_memory.SharedMemory(name=shm.name)
Now comes my first problem. I define the function that will use the array in the shared memory:
def test_function(Input):
c = np.ndarray(a.shape, dtype=np.int64, buffer=existing_shm.buf)
c[1]=100
print(c)
This is incorrect but I don't know how should it be.
Then the main. Is there a role of having the main function to make this work?
if __name__=='__main__':
with Pool(os.cpu_count()) as p:
p.map(test_function, range(12))
It doesn't work.
Do I have to define c in every process? Or I can define it in the main and use it across all processes? I assume that c is a python object and therefore can't be shared by processes due to the gil-lock?
Thank you very much!