You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用multiprocessing.shared_memory共享Numpy数组失败,变量c值异常

多进程共享内存读取异常问题解决

你的问题出在数据类型不匹配:program1里创建的numpy数组a用的是系统默认整型,而program2里硬指定了np.int64作为数据类型,导致字节解析错位,读出来的c就变成了乱码数值。

举个例子:如果你的系统里numpy默认int是int32(每个元素占4字节),那6个元素总字节数是24;但program2里用int64(每个元素占8字节)读取24字节,只能解析出3个元素,剩下的空间用0填充,就会出现你看到的4294967297这类奇怪数值(本质是两个int32的1拼接成了一个int64)。

解决办法

办法1:统一显式指定数据类型

在program1里创建数组时明确指定np.int64,让两边类型一致:

# program1.py 修改后的代码
import numpy as np
from multiprocessing import shared_memory
a = np.array([1, 1, 2, 3, 5, 8], dtype=np.int64)  # 显式指定dtype
shm = shared_memory.SharedMemory(create=True, size=a.nbytes)
b = np.ndarray(a.shape, dtype=a.dtype, buffer=shm.buf)
b[:] = a[:]
print(b)
print(shm.name)

program2的代码保持不变,就能正确读取到c的数值。

办法2:动态传递数组元信息

不要在program2里硬写shape和dtype,通过临时文件传递这些信息,保证两边参数完全一致:

# program1.py 添加保存元信息的代码
import numpy as np
from multiprocessing import shared_memory
import json

a = np.array([1, 1, 2, 3, 5, 8])
shm = shared_memory.SharedMemory(create=True, size=a.nbytes)
b = np.ndarray(a.shape, dtype=a.dtype, buffer=shm.buf)
b[:] = a[:]
# 保存shape和dtype到文件
with open('shm_info.json', 'w') as f:
    json.dump({'shape': a.shape, 'dtype': str(a.dtype)}, f)
print(b)
print(shm.name)
# program2.py 修改后的代码
import numpy as np
from multiprocessing import shared_memory
import json

# 读取元信息
with open('shm_info.json', 'r') as f:
    info = json.load(f)
existing_shm = shared_memory.SharedMemory(name='wnsm_d69eb579')
c = np.ndarray(info['shape'], dtype=np.dtype(info['dtype']), buffer=existing_shm.buf)
print(c)

注意事项

使用完共享内存后,记得调用shm.close()和shm.unlink()释放资源,避免内存泄漏。

内容的提问来源于stack exchange,提问作者B_Snowflake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 21:55:13