In Python 3.8+, is it possible to check whether a numpy array is being stored in shared memory?
In the following example, a numpy array sharedArr
was created using the buffer of a multiprocessing.shared_memory.SharedMemory
object. Will like to know if we can write a function that can detect whether SharedMemory
is used.
import numpy as np
from multiprocessing import shared_memory
if __name__ == '__main__':
# Created numpy array `sharedArr`in shared memory
arr = np.zeros(5)
shm = shared_memory.SharedMemory(create=True, size=arr.nbytes)
sharedArr = np.ndarray(arr.shape, dtype=arr.dtype, buffer=shm.buf)
sharedArr[:] = arr[:]
# How to tell if numpy array is stored in shared memory?
print(type(sharedArr)) # <class 'numpy.ndarray'>
print(hex(id(sharedArr))) # 0x7fac99469f30
shm.close()
shm.unlink()
hex(id(...))
is a huge red herring. It not a useful way to determine what is going on with underyling buffers.id
does not provide the memory address, that is a CPython implementation detail, it is merely a number that is guaranteed unique for the lifetime of an object. In this case, it is the address of the PyObject header of thenp.ndarray
object, but that has nothing to do with the buffer, indeed, you can create an arbitrary number ofnumpy.ndarray
objects with differentid
's that share the same buffer – Reconcilable