我在使用multiprocessing.shared_memory支持 numpy 陣列時遇到錯誤。這是我的使用模式:
# demo.py
from contextlib import contextmanager
from multiprocessing.managers import SharedMemoryManager
from multiprocessing.shared_memory import SharedMemory
from typing import Iterator
import numpy as np
@contextmanager
def allocate_shared_mem() -> Iterator[SharedMemory]:
with SharedMemoryManager() as smm:
shared_mem = smm.SharedMemory(size=80)
yield shared_mem
with allocate_shared_mem() as shared_mem:
shared_arr = np.frombuffer(shared_mem.buf)
assert len(shared_arr) == 10
這是我看到的問題:
$ python demo.py
Exception ignored in: <function SharedMemory.__del__ at 0x7ff8bf604ee0>
Traceback (most recent call last):
File "/home/rig1/miniconda3/envs/pysc/lib/python3.10/multiprocessing/shared_memory.py", line 184, in __del__
File "/home/rig1/miniconda3/envs/pysc/lib/python3.10/multiprocessing/shared_memory.py", line 227, in close
BufferError: cannot close exported pointers exist
我認為問題在于numpy 陣列存在時SharedMemoryManager無法解除分配。shared_mem如果我附加del shared_array到底部的with塊末尾demo.py,問題就會消失。
如何使用由共享記憶體支持的 numpy 陣列,而無需手動考慮陣列洗掉?是否有任何干凈的模式或陣列無效技巧來處理這種情況?
我擔心我的代碼的其他部分會獲取陣列的句柄,并且要弄清楚應該洗掉哪些物件以避免“無法關閉匯出的指標存在”錯誤會很麻煩。如果 numpy 陣列在with塊退出后變得無效,這對我來說很好。
uj5u.com熱心網友回復:
正如官方檔案所做的那樣,您可以numpy.ndarray直接使用初始化程式來創建一個沒有緩沖區管理的陣列。
@contextmanager
def allocate_shared_mem() -> Iterator[SharedMemory]:
with SharedMemoryManager() as smm:
shared_mem = smm.SharedMemory(size=80)
yield shared_mem
def run():
with allocate_shared_mem() as shared_mem:
shared_arr = np.ndarray((10,), dtype=np.float64, buffer=shared_mem.buf)
shared_arr[:] = 1
print(shared_arr) # This should not work, but it does.
run()
請注意,您還可以匯出陣列而不是緩沖區。
@contextmanager
def allocate_shared_mem() -> Iterator[SharedMemory]:
with SharedMemoryManager() as smm:
shared_mem = smm.SharedMemory(size=80)
shared_arr = np.ndarray((10,), dtype=np.float64, buffer=shared_mem.buf)
yield shared_arr
def run():
with allocate_shared_mem() as shared_arr:
shared_arr[:] = 1
print(shared_arr) # This will crash without raising any exception.
run()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/485065.html
