Jan-29-2021, 04:24 AM
I want to make 2 processes that share a numpy array (one of which writes the array and the other reads it).
It works fine when I make 2 processes with 2 functions like this:
The code above gives me 10, but when using subclasses it gives me 0 (Windows 10, Python 3.8.7 64bit).
Why do they print out different results? Have I made a mistake or is this a bug?
It works fine when I make 2 processes with 2 functions like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
from multiprocessing import Process, Semaphore, shared_memory import numpy as np import time def reader( id , a, shm): exst_shm = shared_memory.SharedMemory(name = shm) b = np.ndarray(a.shape, dtype = a.dtype, buffer = exst_shm.buf) time.sleep( 2 ) print ( 'FUNCTION VERSION: ' , b[ 0 ]) def worker( id , a, shm): exst_shm = shared_memory.SharedMemory(name = shm) b = np.ndarray(a.shape, dtype = a.dtype, buffer = exst_shm.buf) b[ 0 ] + = 10 if __name__ = = "__main__" : a = np.array([ 0 ]) shm = shared_memory.SharedMemory(create = True , size = a.nbytes) c = np.ndarray(a.shape, dtype = a.dtype, buffer = shm.buf) th1 = Process(target = reader, args = ( 1 , a, shm.name)) th2 = Process(target = worker, args = ( 2 , a, shm.name)) th1.start() th2.start() th1.join() th2.join() |
Why do they print out different results? Have I made a mistake or is this a bug?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
from multiprocessing import Process, Semaphore, shared_memory import numpy as np import time class Reader(Process): def __init__( self , id , a, shm): Process.__init__( self ) exst_shm = shared_memory.SharedMemory(name = shm) b = np.ndarray(a.shape, dtype = a.dtype, buffer = exst_shm.buf) time.sleep( 2 ) print ( 'SUBCLASS VERSION: ' , b[ 0 ]) class Worker(Process): def __init__( self , id , a, shm): Process.__init__( self ) exst_shm = shared_memory.SharedMemory(name = shm) b = np.ndarray(a.shape, dtype = a.dtype, buffer = exst_shm.buf) b[ 0 ] + = 10 if __name__ = = "__main__" : a = np.array([ 0 ]) shm = shared_memory.SharedMemory(create = True , size = a.nbytes) c = np.ndarray(a.shape, dtype = a.dtype, buffer = shm.buf) th1 = Reader( 1 , a, shm.name) th2 = Worker( 2 , a, shm.name) th1.start() th2.start() th1.join() th2.join() |