use*_*212 11 python numpy multiprocessing multidimensional-array
我需要创建一个多维数组或列表列表的共享对象,以便其他进程可以使用它.有没有办法创建它,就像我所看到的那样是不可能的.我试过了:
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
Run Code Online (Sandbox Code Playgroud)
我听说numpy数组可以是多个数组和共享对象,如果上面不可能有人能告诉我如何使numpy数组成为共享对象?
jfs*_*jfs 24
要使numpy数组成为共享对象(完整示例):
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
Run Code Online (Sandbox Code Playgroud)
如果您不需要共享(如"共享相同的内存")对象,并且只能从多个进程使用的对象就足够了,那么您可以使用multiprocessing.Manager
:
from multiprocessing import Process, Manager
def f(L):
row = L[0] # take the 1st row
row.append(10) # change it
L[0] = row #NOTE: important: copy the row back (otherwise parent
#process won't see the changes)
if __name__ == '__main__':
manager = Manager()
lst = manager.list()
lst.append([1])
lst.append([2, 3])
print(lst) # before: [[1], [2, 3]]
p = Process(target=f, args=(lst,))
p.start()
p.join()
print(lst) # after: [[1, 10], [2, 3]]
Run Code Online (Sandbox Code Playgroud)
来自文档:
服务器进程管理器比使用共享内存对象更灵活,因为它们可以支持任意对象类型.此外,单个管理器可以通过网络由不同计算机上的进程共享.但是,它们比使用共享内存慢.
归档时间: |
|
查看次数: |
11122 次 |
最近记录: |