【问题标题】:Shared memory between 2 processed (application crushed)2 个已处理的共享内存(应用程序崩溃)
【发布时间】:2021-02-14 05:24:03
【问题描述】:

我正在尝试使用multiprocessing.shared_memory 模块在两个进程之间共享pandas.DataFrame

我开始使用 JupyterLab 打开 2 个笔记本,然后我编写了该代码:

为了能够使用copypaste,我也将代码作为文本发布:

# Notebook 1:

from multiprocessing.shared_memory import SharedMemory
import numpy as np
import pandas as pd

values = lambda cast: [cast(value) for value in range(5)]

pd_object = pd.DataFrame(data={'A': values(cast=int), 'B': values(cast=float), 'C': values(cast=str)})
np_object = pd_object.to_numpy(copy=True, dtype='object')

shared_memory = SharedMemory(name='dataframe', create=True, size=np_object.nbytes)
shared_object = np.ndarray(shape=np_object.shape, dtype=np_object.dtype, buffer=shared_memory.buf)

shared_object[:] = np_object
shared_object
# array([[0, 0.0, '0'],
#        [1, 1.0, '1'],
#        [2, 2.0, '2'],
#        [3, 3.0, '3'],
#        [4, 4.0, '4']], dtype=object)

shared_memory.close()
shared_memory.unlink()

# Notebook 2:

from multiprocessing.shared_memory import SharedMemory
import numpy as np
import pandas as pd

shared_memory = SharedMemory(name='dataframe')
shared_object = np.ndarray(shape=(5, 3), dtype=np.object, buffer=shared_memory.buf)

shared_object # here the application crushed without no reason...

pd_object = pd.DataFrame(data=shared_object, columns=['A', 'B', 'C'], dtype='object')
pd_object = pd_object.astype(dtype={'A': 'int64', 'B': 'float64', 'C': 'object'})

shared_memory.close()

问题是应用程序在Notebook 2 上崩溃,我要求查看shared_object 的输出,我不知道为什么会这样......

我试着关注这个documentation

感谢任何可以提供帮助的人!

【问题讨论】:

    标签: python numpy multiprocessing shared-memory


    【解决方案1】:

    共享内存数组不能有对象类型。对象类型数组是指针数组——指针在新的 shell 中将完全无效,python 在尝试访问它们时会出现段错误。

    切换到数字类型。

    【讨论】:

    • 如何共享混合类型的DataFrame?像这个例子,包括(int、float 和 str)
    • 您可以将非字符串列共享为单独的数组。如果你想按原样使用这个数据框,你应该研究其他进行进程间通信的方法。
    猜你喜欢
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 2020-12-19
    • 2020-07-04
    • 2014-05-02
    • 1970-01-01
    相关资源
    最近更新 更多