Python 多处理释放共享数组使用的内存

Python Multiprocessing Freeing up memory used by shared array

有没有办法取消分配共享多处理阵列使用的内存?这是一个代码片段,它创建了一个大约 1 GiB 共享内存的内存块,然后在脚本的其余部分被阻塞。有没有办法在同一个脚本 运行 期间释放内存?

我尝试删除所有引用并通过 gc.collect() 调用垃圾收集器,但这似乎对 运行 期间脚本的内存使用没有任何影响。

import psutil
import gc
import ctypes as cty
import multiprocessing as mpc
import os

def bytes_to_GiB_MiB(n_bytes):
    return n_bytes/2**30, (n_bytes%(2**30))/2**20
    
def print_mem_usage():
    process = psutil.Process(os.getpid()) 
    print "Script Mem Usage {:} GiB {:} MiB".format(*bytes_to_GiB_MiB(process.memory_info().rss))
    return process.memory_info().rss    
    
if __name__=="__main__":
    t_N = 5000
    N=150
    Shape_spl = (t_N+4, N,N) 
    mem0 = print_mem_usage()
    C_shared = mpc.Array(cty.c_double, N*N*(t_N+4))
    mem1 = print_mem_usage()
    print "Mem Difference is {:} GiB {:} MiB".format(*bytes_to_GiB_MiB(mem1-mem0))
    del C_shared
    gc.collect()
    # Do something here such that the memory used by C_shared is free again.
    mem2 = print_mem_usage()
    print "Mem Difference is {:} GiB {:} MiB".format(*bytes_to_GiB_MiB(mem2-mem0))

...记录...这似乎与 python <= 3.7
中的这个错误有关 (如前所述,它应该在 python 3.8 中修复):
https://bugs.python.org/issue32759

讨论中还建议了一个粗略的“修复”,它似乎适用于 python 3.7:
(不确定这是否也适用于 python 2.7)

"... delete the globe _heap and recreate a new one"
mp.heap.BufferWrapper._heap = mp.heap.Heap()