python多进程多维数组数据传递example

import multiprocessing as mp
import numpy as np
def worker(size, idx, arr):
    array = np.zeros((size,size,size))
    print(idx)
    array[idx[0],idx[1],idx[2]] = 100
    for slice in range(size):
        for row in range(size):            
            arr[slice*size*size+row*size:slice*size*size+row*size+size] = array[slice, row, :]  
 

 
if __name__=='__main__':
    size = 3
    myArray_list = []
    for i in range(9):
        myArray_list.append(mp.Array('f', size*size*size))
    ps = [mp.Process(target=worker, args=(size, [x%3,x%3,x%3], myArray_list[x])) for x in range(9)]
    for p in ps:
        p.start()
    for p in ps:
        p.join()
 
    for x in range(9):
        print(x)
        res = np.array(myArray_list[x])
        res1 = res.reshape((size,size,size)) 
        print(res1)
        print(res1[1,2,0])
        
    print('after all workers finished')

多进程数据同步不能用global,因为不能跨进程存取,必须要用Multiprocessing的queue, Value, Array, Rawarray来做数值传递。

而且这个传递不支持多维数组,只支持一维的,所以前后要自己转换一下。

posted on 2018-04-16 16:37  SumXing  阅读(571)  评论(0编辑  收藏  举报

导航