在 Python 3.8+ 中,是否可以检查 numpy 数组是否存储在共享内存中?
在以下示例中,sharedArr
使用对象的缓冲区创建了一个 numpy 数组multiprocessing.shared_memory.SharedMemory
。想知道我们是否可以编写一个可以检测是否SharedMemory
被使用的函数。
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()