【问题标题】:python 3.8 shared memory example giving different valuespython 3.8共享内存示例给出不同的值
【发布时间】:2019-11-20 02:40:38
【问题描述】:

我正在尝试通过此链接https://docs.python.org/3/library/multiprocessing.shared_memory.html 使用 python 3.8 中的新共享内存示例

# In the first Python interactive shell
import numpy as np
a = np.array([1, 1, 2, 3, 5, 8])  # Start with an existing NumPy array
from multiprocessing import shared_memory
shm = shared_memory.SharedMemory(create=True, size=a.nbytes)
# Now create a NumPy array backed by shared memory
b = np.ndarray(a.shape, dtype=a.dtype, buffer=shm.buf)
b[:] = a[:]  # Copy the original data into shared memory
shname = shm.name  # We did not specify a name so one was chosen for us
print(shname)
print(a)
print(b)

# In either the same shell or a new Python shell on the same machine
import numpy as np
from multiprocessing import shared_memory
# Attach to the existing shared memory block
existing_shm = shared_memory.SharedMemory(name=shname)
# Note that a.shape is (6,) and a.dtype is np.int64 in this example
c = np.ndarray((6,), dtype=np.int64, buffer=existing_shm.buf)
print(c)
c[-1] = 888
print(c)
# Back in the first Python interactive shell, b reflects this change

# Clean up from within the second Python shell
del c  # Unnecessary; merely emphasizing the array is no longer used
existing_shm.close()

# Clean up from within the first Python shell
del b  # Unnecessary; merely emphasizing the array is no longer used
shm.close()
shm.unlink()  # Free and release the shared memory block at the very end

在示例中,c 的输出应该是 array([1, 1, 2, 3, 5, 8]) 但是当我运行它时,我得到:

wnsm_26020d1b
[1 1 2 3 5 8]
[1 1 2 3 5 8]
[ 4294967297 12884901890 34359738373           0           0           0]
[ 4294967297 12884901890 34359738373           0           0         888]

我完全错过了什么吗?其他人有这个结果吗?

【问题讨论】:

  • 你使用的是什么操作系统?
  • @user2357112supportsMonica windows,你解决了,谢谢!

标签: python shared-memory python-3.8


【解决方案1】:

您的 c 数组需要使用与 b 相同的 dtype 创建,但事实并非如此。从显示的输出中,我们可以告诉您在 Windows 上,其中 NumPy 的默认整数大小是 32 位,而不是 64。您为第二个数组指定了 np.int64 的 dtype,但是 @ 987654324@ 使用的是 32 位的默认大小。

np.int_ 用于第二个数组以使用NumPy 的默认整数dtype,或者为ac 指定一个显式dtype(b 也将使用它,因为b 的dtype来自a)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 2016-12-13
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多