operating-systems concurrency

Definition

Shared Memory

Shared memory is an IPC mechanism where a region of physical memory is mapped into the address space of multiple processes, allowing direct communication by reading/writing shared locations. Typically the fastest IPC form, avoiding data copying overhead.

Mechanism

Usage Steps

  1. Creation: One process creates a shared memory segment
  2. Mapping: Other processes attach (map) segment into their virtual address space
  3. Access: Processes read/write as if local data

Synchronisation

Manual Synchronisation Required

The OS does not provide automatic protection against concurrent access. Programmers must use synchronisation primitives:

Failure leads to race conditions.

Implementation

POSIX Shared Memory

// 1. Create/open shared memory
int fd = shm_open("/shm_name", O_CREAT | O_RDWR, 0666);
 
// 2. Set size
ftruncate(fd, sizeof(shared_data_t));
 
// 3. Map into address space
shared_data_t *data = mmap(NULL, sizeof(shared_data_t),
                           PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
 
// 4. Use shared memory
data->counter = 42;
 
// 5. Cleanup
munmap(data, sizeof(shared_data_t));
close(fd);
shm_unlink("/shm_name");