Module 9 · 14 min read · Free chapter
Synchronisation and inter-process communication
A race condition arises when the result depends on how concurrent steps interleave. A correct critical-section solution needs mutual exclusion, progress and bounded waiting. Semaphores use wait and signal, and the final value is the start value minus waits plus signals. Producer–consumer uses mutex = 1, empty = n and full = 0.
Start from zero: two counters and one last berth
Imagine a train with only one sleeper berth left. At the same moment two clerks at two windows look at the shared screen, and both see "berth 42 free". Both print a ticket, and two passengers board the train holding the same berth number.
Nothing was wrong with either clerk. Each followed the steps correctly: check, then book. The trouble came because the two sets of steps interleaved, and the second clerk checked before the first had booked.
Computers meet this problem every second. Two threads update a bank balance, two processes append to the same log file, or two cores change the same counter. This chapter shows how the operating system and the hardware make such steps happen one at a time, and how processes pass data to each other safely.
Why it matters. Bugs from interleaving appear only now and then, so they slip through testing and then cost money in production. Every booking system, payment system and database depends on the ideas in this chapter.
Race conditions and the critical-section problem
A statement like counter++ looks like one step, but the CPU does it in three: load counter into a register, add 1, and store it back. Suppose and two threads each run counter++.
T1: load r1 = 5
T2: load r2 = 5
T1: add r1 = 6
T2: add r2 = 6
T1: store counter = 6
T2: store counter = 6 /* one increment lost */
The answer should be 7, but this interleaving gives 6. When the result depends on the order of interleaving, we have a race condition. With counter++ in one thread and counter-- in another, starting from 5, the final value can be 4, 5 or 6.
The code that reads or writes shared data is called the critical section. Each process has an entry section before it, which asks for permission, and an exit section after it, which gives permission back. A correct solution must meet three requirements.
| Requirement | Meaning |
|---|---|
| Mutual exclusion | at most one process is in its critical section at a time |
| Progress | if no one is inside, only processes trying to enter decide who goes next, and the decision is not postponed for ever |
| Bounded waiting | there is a limit on how many times others can enter after a process has asked and before it enters |
We also assume nothing about the relative speed of the processes. A solution that works only if one process is faster is not a solution.
Why it matters. GATE often gives a short piece of entry and exit code and asks which of the three requirements it meets. Checking each requirement separately, with a bad interleaving in mind, is the reliable way to answer.
Peterson's solution and hardware locks
Peterson's solution solves the problem for two processes, P0 and P1, using only ordinary shared variables: a boolean array flag[2], both false at first, and an integer turn. Here is the code for process i, where is the other process.
flag[i] = true; /* I want to enter */
turn = j; /* but you may go first */
while (flag[j] && turn == j)
; /* busy wait */
/* critical section */
flag[i] = false; /* I am out */
The trick is the politeness of turn = j. If both processes want to enter at once, both set their flags, and each sets turn to the other. Only one of the two writes to turn survives, so exactly one process finds the loop condition false and enters.
All three requirements hold. Mutual exclusion holds because turn cannot equal both 0 and 1. Progress holds because a process that does not want to enter has its flag false and cannot block the other, and bounded waiting holds because after one entry by P1, P0 is the next to enter.
One warning matters in practice. Modern processors and compilers may reorder memory operations, which can break Peterson's solution, so real systems add memory barriers or use hardware instructions instead.
The hardware gives atomic instructions that read and change a word in one step that cannot be interrupted. test_and_set returns the old value of a lock and sets it to true.
bool test_and_set(bool *t) { bool old = *t; *t = true; return old; } /* atomic */
while (test_and_set(&lock)) ; /* spin */
/* critical section */
lock = false;
This spinlock gives mutual exclusion, but a process may lose the race again and again, so test_and_set alone does not give bounded waiting. Compare-and-swap is a similar atomic instruction. Disabling interrupts also keeps others out on a single CPU, but it fails on multiprocessors and is unsafe to give to user programs.
Why it matters. Every lock in every operating system rests on an atomic instruction like these. Spinning wastes CPU time, which is why longer waits use blocking semaphores instead.
Semaphores and mutex locks
A semaphore S is an integer that can be touched only through two atomic operations. wait(S), also called P, asks for a unit, and signal(S), also called V, returns one. In the blocking version a process that cannot proceed sleeps in a queue instead of spinning.
wait(S): S = S - 1; if (S < 0) put this process to sleep on S's queue
signal(S): S = S + 1; if (S <= 0) wake one process from S's queue
A counting semaphore can hold any integer and is used for a pool of identical resources, such as 3 printers with . A binary semaphore holds only 0 or 1 and is used as a lock, starting at 1. In the blocking version, if then exactly k processes are asleep on it.
Worked example 1. A counting semaphore starts at 10. Processes then perform 6 wait operations and 4 signal operations in some order. The final value is , whatever the order, because each wait subtracts 1 and each signal adds 1.
Worked example 2. A semaphore starts at 2, and five processes each call wait(S) before anyone signals. The value goes , so two processes are inside and three are asleep in the queue.
Semaphores also impose order. If statement B in process P2 must run after statement A in P1, use a semaphore : P1 runs A then signal(sync), and P2 runs wait(sync) then B.
A mutex lock is a simpler lock with acquire and release. Its key difference from a binary semaphore is ownership: only the thread that acquired a mutex may release it. A semaphore has no owner, so one process can wait and a different process can signal, which is exactly what signalling needs.
Why it matters. Semaphores turn the abstract requirements into two simple calls. GATE numericals on semaphore values and on the order of wait and signal are asked almost every year.
Monitors and the producer–consumer problem
Semaphores are powerful but easy to misuse; a single swapped wait can freeze the system. A monitor moves the locking into the language. It is a module of shared data and procedures in which only one process can be active at a time, and the compiler inserts the lock for you.
For waiting on a condition, a monitor provides condition variables. x.wait() suspends the caller and releases the monitor, and x.signal() resumes exactly one process waiting on x. If no process is waiting, x.signal() does nothing, which is the key difference from a semaphore's signal, which always increments the value.
Now the classic bounded-buffer producer–consumer problem. A producer puts items into a buffer of n slots and a consumer takes them out; the producer must wait when the buffer is full and the consumer when it is empty. Three semaphores solve it: guards the buffer, counts free slots, and counts filled slots.
/* producer */ /* consumer */
wait(empty); wait(full);
wait(mutex); wait(mutex);
add item to buffer; remove item from buffer;
signal(mutex); signal(mutex);
signal(full); signal(empty);
The order of the two waits matters. Suppose the producer did wait(mutex) before wait(empty) while the buffer is full. It would hold the mutex and sleep on empty, and the consumer could never get the mutex to free a slot, so both would be stuck in deadlock. Swapping the two signals, by contrast, is harmless, because signals never block.
Why it matters. Producer–consumer is the pattern behind keyboard buffers, print queues and video streaming. GATE regularly asks what happens when the waits are swapped or a semaphore starts with the wrong value.
Readers–writers and dining philosophers
Readers–writers. A railway enquiry database is read by thousands and updated by a few. Many readers may read together because reading changes nothing, but a writer needs the data to itself. The first readers–writers solution uses read_count, a mutex that protects read_count, and a lock rw_mutex that writers take.
/* reader */
wait(mutex); read_count++; if (read_count == 1) wait(rw_mutex); signal(mutex);
read data;
wait(mutex); read_count--; if (read_count == 0) signal(rw_mutex); signal(mutex);
/* writer */
wait(rw_mutex); write data; signal(rw_mutex);
The first reader locks writers out and the last reader lets them in. This favours readers: if readers keep arriving, a writer may starve. The second readers–writers problem gives writers priority instead, and then readers may starve.
Dining philosophers. Five philosophers sit at a round table with one chopstick between each pair, five in all. To eat, a philosopher needs both the left and the right chopstick. If each picks up the left chopstick with wait(chopstick[i]) and then waits for the right one, and all five start together, each holds one and waits for the next, so the system is in deadlock.
Three standard fixes break the cycle. Allow at most four philosophers at the table at once, make one philosopher pick up the right chopstick first (an asymmetric order), or let a philosopher pick up chopsticks only when both are free, inside a monitor. With five philosophers, at most two can eat at the same time.
Why it matters. These puzzles are small models of real problems: databases are readers–writers, and any set of processes grabbing several locks risks the philosophers' deadlock. The fixes here are the same ideas used to prevent deadlock in general.
Inter-process communication: pipes, messages and shared memory
Processes have separate address spaces, so they need the OS to talk. There are two basic models of inter-process communication (IPC).
In shared memory, the OS maps one region of physical memory into the address spaces of both processes. After that, reading and writing are ordinary memory accesses with no kernel involvement, so this is the fastest method for large data. But the processes must synchronise themselves, usually with semaphores, exactly as in producer–consumer.
In message passing, the kernel provides send(message) and receive(message). Communication can be direct, naming the other process, or indirect, through a mailbox (port) that several processes can share. Each call can be blocking (synchronous), where send waits until the message is received, or non-blocking (asynchronous); when both send and receive block, the meeting is called a rendezvous.
| Feature | Shared memory | Message passing |
|---|---|---|
| Speed for large data | fast after setup | slower: a system call per message |
| Synchronisation | done by the processes | built into send and receive |
| Across machines | no | yes, as in sockets |
A pipe is the simplest channel. An ordinary pipe, made by pipe(), is one-way, with a read end and a write end, and it joins related processes such as a parent and the child it forks. A named pipe or FIFO has a name in the file system, so unrelated processes can open it, and two pipes are needed for two-way talk.
When you type ls | sort in a shell, the shell makes a pipe, forks two children, and connects the output of ls to the input of sort. Neither program knows the other exists.
Why it matters. Every multi-process program, from a web server to a shell pipeline, needs one of these channels. Choosing between them is a trade-off between speed and safety that system designers make every day.
Descriptive lens: how written papers ask this
Written papers for IT officer posts, state Assistant Programmer exams and university-level tests ask about synchronisation in four ways:
- Define a race condition and the critical-section problem with its three requirements.
- Write a semaphore solution to a classic problem, such as producer–consumer or readers–writers, and explain each line.
- Analyse a given piece of code and say which requirements it meets or where it can deadlock.
- Compare IPC mechanisms or synchronisation tools, such as semaphores and monitors, for a stated application.
Practice questions (our own, not previous-year questions).
- What is a race condition? Explain the three requirements of a correct critical-section solution and show that Peterson's solution meets all three. (15 marks)
- Give a semaphore solution to the bounded-buffer producer–consumer problem and explain what goes wrong if the producer's two wait operations are swapped. (10 marks)
- Compare shared memory and message passing as methods of inter-process communication, with one example of where each is preferred. (10 marks)
Answer plan for question 2.
- State the problem as a producer and a consumer sharing a buffer of n slots, with waiting needed when it is full or empty.
- Name the three semaphores and their starting values, , and , and say what each counts.
- Write the producer and consumer code side by side and explain that the counting semaphores handle waiting while mutex protects the buffer.
- Show the swapped order in the producer, where wait(mutex) comes before wait(empty).
- Trace the case of a full buffer, where the producer holds mutex and sleeps on empty while the consumer blocks on mutex.
- Conclude that this is a deadlock and that waits on counting semaphores must come before the wait on mutex, while the order of signals does not matter.
Quick revision
- A race condition means the result depends on how the steps of concurrent processes interleave.
- A correct critical-section solution needs mutual exclusion, progress and bounded waiting.
- Peterson's solution uses flag[2] and turn and meets all three requirements for two processes.
- test_and_set is atomic, and a spinlock built from it lacks bounded waiting by itself.
- wait decrements and may block, while signal increments and may wake a process.
- The final semaphore value equals the initial value minus the number of waits plus the number of signals.
- A mutex has an owner, while a semaphore does not.
- A monitor gives mutual exclusion automatically, and its signal is lost if no one waits.
- Producer–consumer uses , and , with the counting wait before the mutex wait.
- In the first readers–writers solution writers can starve, and dining philosophers deadlock if all take the left chopstick.
- Shared memory is fastest, message passing is safer and works across machines, and an ordinary pipe is one-way.