Sub topic 2
Communicating through shared memory
This chapter assumes you know what a process is, how the address space of a process is laid out, and that the scheduler can preempt a process at any instruction. You should also be able to read C-like pseudocode.
The idea
Normally each process has a private address space. One process cannot read or write another's variables. Shared memory IPC removes that wall for one region. The operating system maps the same physical memory pages into the address spaces of two or more processes. After that, a store by one process is visible to a load by another, with no system call in between.
The kernel is involved only in setup and teardown:
- One process asks the kernel to create a shared region.
- Each participating process asks the kernel to attach (map) it.
- The processes read and write the region as ordinary memory.
- Each process detaches, and one of them asks the kernel to remove the region.
Why it is fast, and what it costs
With message passing, every transfer goes through a system call, and the kernel copies the data into a kernel buffer and out again. With shared memory, only the setup needs the kernel. Later accesses run at normal memory speed. This makes shared memory the fastest IPC mechanism for large volumes of data.
The cost is that the kernel no longer coordinates access. The processes must agree on a data layout, and they must make sure that two of them do not update the same data at the same time. The rest of this tutorial deals with that problem. GATE questions often state the trade-off as follows.
| Property | Shared memory | Message passing |
|---|---|---|
| Kernel involved | Only at setup and teardown | On every send and receive |
| Speed for large data | Fast, no copying through the kernel | Slower, data is copied |
| Synchronisation | Programmer's responsibility | Built into send and receive |
| Works across machines | No, same machine only | Yes, with sockets |
| Typical use | Large data, many reads and writes | Small messages, distributed systems |
Creating a shared region
On POSIX systems there are three common routes.
- POSIX shared memory:
shm_opencreates a named object,ftruncatesets its size, andmmapwithMAP_SHAREDmaps it. Unrelated processes can attach by using the same name. - System V shared memory:
shmgetcreates or finds a segment by key,shmatattaches it,shmdtdetaches it, andshmctlremoves it. - Anonymous shared mapping:
mmapwithMAP_SHARED | MAP_ANONYMOUScreates a region with no name. It is inherited by child processes created withfork, so it only connects related processes.
The following program uses the third route. The child writes a string and the parent reads it after the child exits. It compiles with gcc on Linux.
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
char *shared = mmap(NULL, 4096, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (shared == MAP_FAILED) return 1;
if (fork() == 0) {
strcpy(shared, "hello from child");
return 0;
}
wait(NULL);
printf("parent read: %s\n", shared);
munmap(shared, 4096);
return 0;
}The wait(NULL) call is the only synchronisation here. It guarantees the child has finished writing before the parent reads. Without it, the parent could print an empty string.
Threads share memory by default
Threads of one process already share the code, data, and heap segments. Only each thread's stack and registers are private. So two threads can communicate through a global variable with no setup at all. This is convenient, and it is also why race conditions appear so easily in multithreaded code. Everything said about synchronisation in the next chapters applies to threads in the same way as to processes with a shared region.
The producer-consumer pattern
The standard example of shared-memory communication is a producer process that creates items and a consumer process that uses them. They share a buffer in the shared region. Two kinds of buffer exist:
- An unbounded buffer has no practical size limit. The consumer may have to wait for items, but the producer never waits.
- A bounded buffer has a fixed size. The consumer waits when the buffer is empty, and the producer waits when it is full.
The textbook implementation of a bounded buffer is a circular array with two indices. in is the next free slot, and out is the first full slot.
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int in = 0; /* next free slot */
int out = 0; /* first full slot */
void put(int item) {
while (((in + 1) % BUFFER_SIZE) == out)
; /* buffer full: busy wait */
buffer[in] = item;
in = (in + 1) % BUFFER_SIZE;
}
int get(void) {
while (in == out)
; /* buffer empty: busy wait */
int item = buffer[out];
out = (out + 1) % BUFFER_SIZE;
return item;
}The buffer is empty when in == out. It is full when (in + 1) % BUFFER_SIZE == out. Because the full test must be told apart from the empty test, one slot is always left unused. This buffer holds at most BUFFER_SIZE - 1 items. A common GATE question asks for this capacity.
This code is correct only in a restricted setting: exactly one producer, exactly one consumer, and memory operations that the hardware does not reorder. Only the producer writes in, and only the consumer writes out, so the two never update the same variable. With two producers, both may read the same in, store into the same slot, and lose an item. On modern CPUs and compilers, even the single-producer case needs memory barriers or atomic types so that the store to buffer[in] becomes visible before the store to in.
The busy-wait loops also waste CPU time. The semaphore solution in a later chapter replaces them with blocking.
Common errors
- Assuming shared means safe. Shared memory gives no mutual exclusion. Any read-modify-write on shared data, such as
count++, can interleave with another process. - Storing pointers in the region. Each process may map the region at a different virtual address. A pointer into the region that is valid in one process can point to nothing in another. Use offsets from the start of the region instead.
- Forgetting cleanup. Named POSIX objects and System V segments outlive the processes that made them. Call
shm_unlinkorshmctl(..., IPC_RMID, ...)or they stay in the system. - Reading before the writer has finished. A consumer needs an explicit signal, such as a flag, a semaphore, or
wait, to know the data is complete.
Exercise
A bounded buffer is implemented as a circular array of size 8 with indices in and out, using the full test (in + 1) % 8 == out and the empty test in == out. One producer and one consumer share it. (a) What is the largest number of items it can hold? (b) Why do two producers break the code?
Show answer
(a) It holds at most 7 items. If it held 8, in would equal out again, and the full buffer would look empty, so one slot stays unused. (b) Both producers can read the same value of in before either updates it. They then write to the same slot, and one item is overwritten. They can also both increment in from stale values, so a slot is skipped or an update is lost. The code needs mutual exclusion between producers.
Exercise
A parent process declares int x = 0; as a global and calls fork(). The child sets x = 5 and exits. The parent then calls wait(NULL) and prints x. What does it print, and what would you change so the parent sees 5?
Show answer
It prints 0. After fork, the child has a private copy of the parent's pages, so the child's write changes only its own copy. To share the variable, place it in a region mapped with MAP_SHARED (for example, an anonymous mmap created before fork) and access x through a pointer into that region.