I thought that SharedMemory would keep values of target arrays, but when I actually tried it, it seems it doesn't.
from multiprocessing import Process, Semaphore, shared_memory
import numpy as np
import time
dtype_eV = np.dtype({ 'names':['idx', 'value', 'size'], \
'formats':['int32', 'float64', 'float64'] })
def worker_writer(id, number, a, shm):
exst_shm = shared_memory.SharedMemory(name=shm)
b = np.ndarray(a.shape, dtype=a.dtype, buffer=exst_shm.buf)
for i in range(5):
time.sleep(0.5)
b['idx'][i] = i
def worker_reader(id, number, a, shm):
exst_shm = shared_memory.SharedMemory(name=shm)
b = np.ndarray(a.shape, dtype=a.dtype, buffer=exst_shm.buf)
for i in range(5):
time.sleep(1)
print(b['idx'][i], b['value'][i])
if __name__ == "__main__":
a = np.zeros(5, dtype=dtype_eV)
a['value'] = 100
shm = shared_memory.SharedMemory(create=True, size=a.nbytes)
c = np.ndarray(a.shape, dtype=a.dtype, buffer=shm.buf)
th1 = Process(target=worker_writer, args=(1, 50000000, a, shm.name))
th2 = Process(target=worker_reader, args=(2, 50000000, a, shm.name))
th1.start()
th2.start()
th1.join()
th2.join()
'''
result:
0 0.0
1 0.0
2 0.0
3 0.0
4 0.0
'''
In the code above, the 2 processes can share one array(a) and access to it. But the value that was given before sharing(a['value'] = 100) is missing. Is it just natural or is there any way to keep the value even after sharing?