是否可以在内存映射文件中存储 python 个对象(特别是 sklearn 模型)?

Is it possible to store python objects (specifically sklearn models) in memory mapped files?

我有几个占用大量内存的大对象(sklearn 模型),我想在多个进程之间共享它们。 有办法吗?

在进程从同一个 python 脚本启动的条件下,这里是创建第二个进程并在两个进程之间共享变量的示例。对此进行详细说明以创建一些流程是很简单的。注意用于创建和访问共享变量和锁的结构。我在算术过程中插入了一个循环以生成一些 cpu 用法,以便您可以监视并查看它在多核或多处理器平台上的运行情况。还要注意使用共享变量来控制第二个进程,在本例中是告诉它何时退出。最后,共享对象可以是值或数组,参见 https://docs.python.org/2/library/multiprocessing.html

#!/usr/bin/python

from time import sleep
from multiprocessing import Process, Value, Lock

def myfunc(counter, lock, run):

    while run.value:
        sleep(1)
        n=0
        for i in range(10000):
            n = n+i*i
        print( n )
        with lock:
            counter.value += 1
            print( "thread %d"%counter.value )

    with lock:
        counter.value = -1
        print( "thread exit %d"%counter.value )

# =======================

counter = Value('i', 0)
run = Value('b', True)
lock = Lock()

p = Process(target=myfunc, args=(counter, lock, run))
p.start()

while counter.value < 5:
    print( "main %d"%counter.value )
    n=0
    for i in range(10000):
        n = n+i*i
    print( n )
    sleep(1)

with lock:
    counter.value = 0

while counter.value < 5:
    print( "main %d"%counter.value )
    sleep(1)

run.value = False

p.join()

print( "main exit %d"%counter.value)