我需要创建一个多维数组或列表列表的共享对象,以便其他进程可以使用它。有没有办法创建它,就像我所看到的那样是不可能的。我试过了:
from multiprocessing import Process, Value, Array
arr = Array('i', range(10))
arr[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
arr[2]=[12,43]
TypeError: an integer is required
我听说numpy数组可以是多个数组和共享对象,如果上面不可能有人可以告诉我如何将numpy数组作为共享对象吗?
答案 0 :(得分:23)
使numpy数组成为共享对象(full example):
import ctypes as c
import numpy as np
import multiprocessing as mp
n, m = 2, 3
mp_arr = mp.Array(c.c_double, n*m) # shared, can be used from multiple processes
# then in each new process create a new numpy array using:
arr = np.frombuffer(mp_arr.get_obj()) # mp_arr and arr share the same memory
# make it two-dimensional
b = arr.reshape((n,m)) # b and arr share the same memory
如果您不需要共享(如“共享同一内存”)对象,只需要可以从多个进程使用的对象即可,您可以使用{{1} }:
multiprocessing.Manager
来自the docs:
服务器进程管理器比使用共享内存更灵活 对象,因为它们可以支持任意对象类型。 此外,单个管理器可以由不同的进程共享 通过网络的计算机。但是,它们比使用共享慢 存储器中。
答案 1 :(得分:2)
为什么不创建Array
的列表?
arrays = [Array('i', range(10))] * 10