shared_memory allows memory sharing between processes without serialization.
1from multiprocessing import Process, shared_memory2import numpy as np34def worker(shm_name, shape, dtype):5 existing_shm = shared_memory.SharedMemory(name=shm_name)6 arr = np.ndarray(shape, dtype=dtype, buffer=existing_shm.buf)7 arr *= 2 # Modify shared data8 existing_shm.close()910if __name__ == "__main__":11 # Create shared array12 arr = np.array([1, 2, 3, 4, 5], dtype=np.int32)13 shm = shared_memory.SharedMemory(create=True, size=arr.nbytes)14 shared_arr = np.ndarray(arr.shape, dtype=arr.dtype, buffer=shm.buf)15 shared_arr[:] = arr[:] # Copy data1617 # Process modifies shared memory18 p = Process(target=worker, args=(shm.name, arr.shape, arr.dtype))19 p.start()20 p.join()2122 print(shared_arr) # [2, 4, 6, 8, 10]23 shm.close()24 shm.unlink()
Benefits:
Use cases: