问题
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