python - 如何更改多处理共享数组大小?

标签 python multiprocessing ctypes python-multiprocessing

我想创建一个具有动态大小的共享数组。我想在另一个进程中为其分配一个未知大小的数组。

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[:]

最佳答案

mp.Arrays 的大小只能在实例化时设置一次。您可以使用 mp.Manager创建 shared list然而:

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[:])

产量

[3, 5, 7]
<小时/>

另请注意 args=(arr) 结果为

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

因为 args 期望将参数序列传递给它。 (参数) 计算结果为arr。要将 arr 传递给 f,您需要 args=[arr]args=(arr,)(包含 1 个元素的元组)。

关于python - 如何更改多处理共享数组大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33330297/

相关文章:

python - Pygame 在不同颜色的矩形上移动图像

c++ - 多处理=多个进程运行?

python - 使用 pyzmq 与子进程通信

python - 构建 DLL (MyMathFuncs) 以在 Python Ctypes 中使用

python - 如何在 64 位环境中处理 ctypes 中的字符串数组 (char **)?

python - 如何在python中引用类变量

python - 将大型 JSON 文件一次拆分为 100 个批处理,以便通过 API 运行

python - 使用 Scikit-Learn 的 SVR,如何在预测目标时结合分类特征和连续特征?

python - multiprocessing.freeze_support()

Python:将 ctypes_ubyte 数组转换为字符串