首页 > 解决方案 > 在 Python3.8 的多进程 SharedMemory 中共享字节对象

问题描述

我有一个大字节对象,我想将它放入 SharedMemory 中,以便我的多处理任务可以访问它。我正在使用文档中描述的ShareableList

from multiprocessing import shared_memory
s2v_a = Sense2Vec().from_disk(SENSE2VEC_FOLDER)
s2v_a_bytes = s2v_a.to_bytes()
print(sys.getsizeof(s2v_a_bytes)) #prints <class 'bytes'>
print(type(s2v_a_bytes)) #prints 4220733334 (4.2Gb)
memory = shared_memory.ShareableList([s2v_a_bytes])

但是,当我尝试创建 ShareableList 时,我得到一个 AssertionError 格式不小于 8。我可以看到这与struct packing format有关。

Traceback (most recent call last):
  File "/home/user/anaconda3/envs/uniqueness/lib/python3.8/runpy.py", line 193, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/home/user/anaconda3/envs/uniqueness/lib/python3.8/runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "/home/user/dev/uniqueness/backend/app/coding.py", line 39, in <module>
    memory = shared_memory.ShareableList([s2v_a_bytes])
  File "/home/user/anaconda3/envs/uniqueness/lib/python3.8/multiprocessing/shared_memory.py", line 295, in __init__
    assert sum(len(fmt) <= 8 for fmt in _formats) == self._list_len
AssertionError

来自代码的评论

Because values are packed into a memoryview as bytes, the struct
    packing format for any storable value must require no more than 8
    characters to describe its format."""

但据我所知,我没有做任何与文档不同的事情。

标签: pythonshared-memorysense2vec

解决方案


bytes文档说明 for和strin的最大大小为ShareableList10M 字节。4.2 GB 远远超过这个限制。


推荐阅读