【问题标题】:How to resize a shared memory in Python如何在 Python 中调整共享内存的大小
【发布时间】:2016-12-08 10:59:50
【问题描述】:

我想使用一个数组作为共享内存。问题是程序的结构是在我知道共享数组的大小之前生成子进程。如果我发送消息以扩展数组,则不会发生任何事情,并且如果我尝试发送共享数组本身,则会出现错误。下面是一个小脚本来演示我的问题。

import multiprocessing as mp 
import numpy as np

def f(a,pipe):
    while True:
        message, data = pipe.recv()
        if message == 'extend':
            a = np.zeros(data)
            print a
        elif message == 'exit':
            break


if __name__ == '__main__':

    unshared_arr = np.zeros(1)
    a = mp.Array('d', unshared_arr)

    p1,p2 = mp.Pipe()

    p = mp.Process(target=f, args=(a,p2))
    p.start()


    p1.send(('extend', 10))

    p1.send(('exit', None))

    p.join()

    b = np.frombuffer(a.get_obj())

【问题讨论】:

  • a = np.zeros(data) 即使在同一个进程中,也不会在函数调用之外产生任何影响。
  • 是的,但我尝试将a 声明为全局变量,而不是将其作为进程和f 中的输入参数,但我仍然无法让它工作。

标签: python python-2.7 numpy python-multiprocessing


【解决方案1】:

试试:

unshared_Arr = mp.Array(ctypes.c_uint8,SIZE_NEEDED) #should be size 
                                                    #and not the array itself
np_shared = np.frombuffer(ushared_Arr.get_obj(),dtype=ctypes.c_uint8)
np_shared.reshape(SIZE_NEEDED/2,SIZE_NEEDED/2)  #or (,SIZE_NEEDED) ie. any shape 
                                                #you want as long as the allocated size 
                                                #does not change

现在像使用任何 numpy 数组一样使用 np_shared。如果多个进程都需要它,您应该保持它是全局的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-09
    • 2015-08-18
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多