🧠 What is Shared Memory?

Shared Memory is an IPC mechanism where two or more processes map the same region of physical memory into their own address spaces, allowing them to directly read/write data without going through the kernel every time.

This is the fastest IPC method because it avoids system calls after setup.


🔁 How Shared Memory Works

  1. One process creates a shared memory segment using a system call (e.g., shmget in Linux).

  2. Other processes attach to that same segment (shmat).

  3. Now all processes can read and write to the same memory region.

But here’s the catch:

There’s no built-in synchronization — you must use semaphores, mutexes, or spinlocks to avoid race conditions.


📦 Characteristics of Shared Memory

FeatureDescription
⚡ SpeedVery fast (direct memory access)
🧠 VisibilityChanges are instantly visible to other processes
🚫 RiskCan cause data races, corruption without locks
🪢 Sync RequiredYes — must use semaphores, locks, or atomic ops
📚 Setup OverheadNeeds initial coordination via system calls
🌍 ScopeCan work across unrelated processes on the same machine

🛠️ Common APIs (Linux example)

FunctionPurpose
shmget()Create shared memory segment
shmat()Attach shared memory to process
shmdt()Detach shared memory
shmctl()Control operations (delete, info)

🔍 Code Snippet (C - Linux Style)

int id = shmget(IPC_PRIVATE, 1024, IPC_CREAT | 0666);
char *data = (char *) shmat(id, NULL, 0);
strcpy(data, "Hello from Process A");
// Process B reads from the same segment

But you’ll also need a semaphore or mutex to control access.


🧠 Real-World Analogy

Imagine a whiteboard in a shared room. Everyone can write/read from it.
But without rules, two people might overwrite each other’s notes — that’s why you need a marker-passing protocol (like a semaphore).


🔄 Shared Memory vs Other IPCs

FeatureShared MemoryPipes / Queues
🔁 PerformanceVery highMedium (kernel copies)
🪢 SynchronizationManual (you must handle)Automatic (OS-managed)
📤 Setup OverheadMediumLow
📍 Use CaseHigh-throughput, low-latencySimpler communication

🧠 Interview-Ready Definition:

Shared Memory is a high-performance IPC mechanism that allows multiple processes to share a portion of physical memory for direct communication. It requires explicit synchronization and is commonly used when speed and data sharing are critical.