我在尝试访问共享内存时一直出现段错误,我已经将其简化为以下示例。f1
和f2
是完全相同的,只是我在f2
中将共享内存对象存储在额外的变量中,但是f2
可以工作而f1
会导致段错误。为什么会发生这种情况?
(以相反的顺序调用两个函数不会改变行为。)
from multiprocessing import shared_memory
import numpy as np
segment_name = "segment"
data_shape = (5,5,5)
def get_view(shm):
shape = (1,) + data_shape
arr_one = np.ndarray(shape, dtype=np.float64, buffer=shm.buf)
arr_two = np.ndarray(data_shape, dtype=np.float64, buffer=arr_one[0])
return arr_two
def f1():
arr = get_view(shared_memory.SharedMemory(name=segment_name))
print(arr[0][0][0])
def f2():
shm = shared_memory.SharedMemory(name=segment_name)
arr = get_view(shm)
print(arr[0][0][0])
if __name__ == '__main__':
shape = (1,) + data_shape
dummy = np.ndarray(shape, dtype=np.float64)
shared_memory.SharedMemory(name=segment_name, create=True, size=dummy.nbytes)
f2()
f1()