Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing and editing numpy array in python multiprocessing

I was experimenting on numpy with multiprocessing in python I've read numerous tutorials and stackoverflow answers. I wrote a code :

from multiprocessing import Process, Array
import numpy as np

def main():
    im_arr = np.array([[1,2,3],[4,6,7]])
    print('Array in main before process:',im_arr)

    shape = im_arr.shape
    size = im_arr.size
    im_arr.shape = size
    arr = Array('B', im_arr)   
    p = Process(target=fun, args=(arr,shape))
    p.start()
    p.join()

    arr = np.frombuffer(arr.get_obj(), dtype=np.uint8)
    arr.shape = shape
    print('Array in main after process:',arr)

def fun(a, shape):
    a = np.frombuffer(a.get_obj(), dtype=np.uint8)
    a.shape = shape

    a[0][0] = 10
    a = np.array([[0,0,0],[0,0,0]])
    a[0][0] = 5

    print('Array inside function:',a)
    a.shape = shape[0]*shape[1]

if __name__ == '__main__':
    main()

What i hoped to do was to share a numpy array and to edit the array in another process while the change can also be observed in main program. But the output i get is as follows

('Array in main before process:', array([[1, 2, 3],
       [4, 6, 7]]))
('Array inside function:', array([[5, 0, 0],
       [0, 0, 0]]))
('Array in main after process:', array([[10,  2,  3],
       [ 4,  6,  7]], dtype=uint8))

it seems like 'a' in the function behaves like a new independent object after the numpy array is saved to it.

Please correct what i'm doing wrong.

like image 461
PunyCode Avatar asked Aug 07 '26 10:08

PunyCode


1 Answers

it seems like 'a' in the function behaves like a new independent object after the numpy array is saved to it.

Well, this is partly true. With np.array([[0,0,0],[0,0,0]]) you create a new independent object and then with a = attach the label a to it. From then on the label a doesn't point to the shared array anymore.

If you want to save a new array in the shared memory you can use

a[...] = np.array([[0,0,0],[0,0,0]])

(This is actually valid syntax, ... is called the ellipsis literal)

like image 99
user7138814 Avatar answered Aug 09 '26 01:08

user7138814



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!