Use numpy array in shared memory for multiprocessing

后端 未结 5 1555
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 03:51

I would like to use a numpy array in shared memory for use with the multiprocessing module. The difficulty is using it like a numpy array, and not just as a ctypes array.

5条回答
  •  长情又很酷
    2020-11-22 04:23

    You can use the sharedmem module: https://bitbucket.org/cleemesser/numpy-sharedmem

    Here's your original code then, this time using shared memory that behaves like a NumPy array (note the additional last statement calling a NumPy sum() function):

    from multiprocessing import Process
    import sharedmem
    import scipy
    
    def f(a):
        a[0] = -a[0]
    
    if __name__ == '__main__':
        # Create the array
        N = int(10)
        unshared_arr = scipy.rand(N)
        arr = sharedmem.empty(N)
        arr[:] = unshared_arr.copy()
        print "Originally, the first two elements of arr = %s"%(arr[:2])
    
        # Create, start, and finish the child process
        p = Process(target=f, args=(arr,))
        p.start()
        p.join()
    
        # Print out the changed values
        print "Now, the first two elements of arr = %s"%arr[:2]
    
        # Perform some NumPy operation
        print arr.sum()
    

提交回复
热议问题