How to change multiprocessing shared array size?

…衆ロ難τιáo~ 提交于 2020-03-24 13:36:12

问题


I want to create a shared array with a dynamic size. I want to assign an array with an unknown size to it in another process.

from multiprocessing import Process, Value, Array


def f(a):
    b=[3,5,7]
    #resize(a,len(b)) # How to resize "a" ???
    a[:]=b  # Only works when "a" is initialized with the same size like the "b"


arr = Array('d', 0) #Array with a size of 0

p = Process(target=f, args=(arr))
p.start()
p.join()

print arr[:]

回答1:


The size of mp.Arrays can only be set once upon instantiation. You could use a mp.Manager to create a shared list however:

import multiprocessing as mp

def f(mlist):
    b = [3, 5, 7]
    mlist[:]=b  

if __name__ == '__main__':
    manager = mp.Manager()
    mlist = manager.list()
    p = mp.Process(target=f, args=[mlist])
    p.start()
    p.join()

    print(mlist[:])

yields

[3, 5, 7]

Note also args=(arr) results in

TypeError: f() takes exactly 1 argument (0 given)

because args expects a sequence of arguments to be passed to it. (args) evaluates to arr. To pass arr to f you would need args=[arr] or args=(arr,) (a tuple containing 1 element).



来源:https://stackoverflow.com/questions/33330297/how-to-change-multiprocessing-shared-array-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!