簡體   English   中英

如何在Python中調整共享內存的大小

[英]How to resize a shared memory in Python

我想將數組用於共享內存。 問題是程序的結構是這樣的:在我知道共享數組的大小之前就生成了子進程。 如果我發送消息以擴展數組,則什么也不會發生,並且如果我嘗試發送共享數組本身,則會收到錯誤消息。 以下是一個演示我的問題的小腳本。

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())

嘗試:

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。 如果需要多個流程,則應將其保持全局。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM