Making my NumPy array shared across processes

前端 未结 2 1533
[愿得一人]
[愿得一人] 2020-12-31 10:39

I have read quite a few of the questions on SO about sharing arrays and it seems simple enough for simple arrays but I am stuck trying to get it working for the array I have

2条回答
  •  北海茫月
    2020-12-31 11:29

    from multiprocessing import Process, Array
    import numpy as np
    import time
    import ctypes
    
    def fun(a):
        a[0] = -a[0]
        while 1:
            time.sleep(2)
            #print bytearray(a.get_obj())
            c=np.frombuffer(a.get_obj(),dtype=np.float32)
            c.shape=3,3
            print 'haha',c
    
    
    def main():
        a = np.random.rand(3,3).astype(np.float32)
        a.shape=1*a.size
        #a=np.array([[1,3,4],[4,5,6]])
        #b=bytearray(a)
        h=Array(ctypes.c_float,a)
        print "Originally,",h
    
        # Create, start, and finish the child process
        p = Process(target=fun, args=(h,))
        p.start()
        #p.join()
        a.shape=3,3
        # Print out the changed values
        print 'first',a
        time.sleep(3)
        #h[0]=h[0]+1
        print 'main',np.frombuffer(h.get_obj(), dtype=np.float32)
    
    
    
    if __name__=="__main__":
        main()
    

提交回复
热议问题