Definition
Shared Memory
Shared memory is an inter-process communication mechanism in which the operating system maps the same memory object into the virtual address spaces of several processes on the same host. Processes exchange data through ordinary loads and stores to the shared storage.
For resident shared pages, let
and translate virtual addresses to physical memory locations. If and are the bases of mappings of the same bytes, then Corresponding byte offsets refer to the same storage, even when the virtual addresses differ.
Selected virtual pages and four bytes of the shared physical page are shown. Addresses
0x4000in A and0x9000in B both refer to the byte at offset zero, containing42.
Synchronisation
Shared Storage Is Not a Synchronisation Protocol
Sharing memory does not make compound operations atomic or establish the order in which processes exchange data. Unsynchronised conflicting accesses can cause race conditions.
- Mutual exclusion protects updates that must not overlap.
- Condition synchronisation ensures that a reader waits until the required data is ready.
Use primitives that support communication between processes, such as inter-process semaphores, process-shared mutexes or a suitable atomic protocol. Shared storage and its synchronisation objects must be initialised before peers use them.
Costs
Shared memory can avoid repeated copying and system calls for data exchange. It is not invariably the fastest IPC mechanism: setup, page faults, synchronisation and cache-coherence traffic still have costs.