Python 不支持独立进程之间的共享内存。你可以用 C 语言实现你自己的,或者SharedArray
在你使用 libsvm、numpy.ndarray、scipy.sparse 时使用。
pip install SharedArray
def test ():
def generateArray ():
print('generating')
from time import sleep
sleep(3)
return np.ones(1000)
a = Sarr('test/1', generateArray)
# use same memory as a, also work in a new process
b = Sarr('test/1', generateArray)
c = Sarr('test/1', generateArray)
import re
import SharedArray
import numpy as np
class Sarr (np.ndarray):
def __new__ (self, name, getData):
if not callable(getData) and getData is None:
return None
self.orig_name = name
shm_name = 'shm://' + re.sub(r'[./]', '_', name)
try:
shm = SharedArray.attach(shm_name)
print('[done] reuse shared memory:', name)
return shm
except Exception as err:
self._unlink(shm_name)
data = getData() if callable(getData) else getData
shm = SharedArray.create(shm_name, data.size)
shm[:] = data[:]
print('[done] loaded data to shared memory:', name)
return shm
def _unlink (name):
try:
SharedArray.delete(name[len('shm://'):])
print('deleted shared memory:', name)
except:
pass
if __name__ == '__main__':
test()