Sub topic 16
Deadlock caused by wrong semaphore ordering
This chapter assumes you can read wait and signal on binary and counting semaphores, and that you know the bounded-buffer solution from the producer-consumer chapter. It shows how a correct set of semaphores becomes a deadlock when the order of operations is wrong, and how to spot that in a GATE question.
What deadlock means here
A set of processes is deadlocked when each one waits for an event that only another process in the set can cause. With semaphores, the event is a signal call. If every process in the set is blocked inside wait, and the only signal calls that could wake them sit after those blocked wait calls, no process can ever run again.
Deadlock is different from starvation. In starvation, other processes keep making progress while one process waits indefinitely, as with writers in the readers-preference solution. In deadlock, every process in the set is stuck.
The four necessary conditions
Deadlock can occur only if all four conditions hold at the same time. These are the Coffman conditions.
| Condition | How it appears with semaphores |
|---|---|
| Mutual exclusion | A binary semaphore lets only one process hold the resource. |
| Hold and wait | A process keeps one semaphore while blocked on another. |
| No preemption | The OS cannot take a semaphore back. Only the holder calls `signal`. |
| Circular wait | P1 waits for something P2 holds, and P2 waits for something P1 holds, possibly through a longer chain. |
The first three are properties of the tool, so you rarely give them up. The practical fixes therefore target circular wait or hold and wait.
Case 1: swapping the waits in producer-consumer
The correct bounded-buffer code waits on the counting semaphore (empty or full) first and on mutex second. Now swap the two waits in the producer:
void producer(void) {
while (1) {
item = produce_item();
wait(mutex); /* wrong: mutex taken first */
wait(empty); /* may block while holding mutex */
insert_item(item);
signal(mutex);
signal(full);
}
}Take a buffer with N = 1 that is already full. The semaphore values are empty = 0, full = 1, mutex = 1. Trace one interleaving:
- The producer runs
wait(mutex). Nowmutex = 0. - The producer runs
wait(empty). Sinceempty = 0, it blocks while holdingmutex. - The consumer runs
wait(full). Sincefull = 1, it succeeds andfull = 0. - The consumer runs
wait(mutex). Sincemutex = 0, it blocks.
The producer waits for signal(empty), which only the consumer can send, and the consumer sends it only after getting mutex. The consumer waits for mutex, which only the producer can release, and the producer releases it only after empty becomes positive. That is a circular wait.
The same failure happens in the consumer if you swap its waits and the buffer is empty. The consumer takes mutex, blocks on full, and the producer then blocks on mutex and can never signal full.
The rule behind the correct code is this: wait for the condition semaphore (empty, full) before the lock semaphore (mutex). Never block on a condition while holding the lock that the other side needs.
Case 2: two locks in opposite order
The classic form uses two binary semaphores, A and B, both initialised to 1. Process P1 acquires A then B. Process P2 acquires B then A. The following program is runnable with POSIX semaphores. Compile it with gcc -pthread deadlock.c. The sleep calls make the bad interleaving almost certain, and the program then hangs.
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>
sem_t a, b;
void *p1(void *arg) {
sem_wait(&a);
sleep(1);
sem_wait(&b);
printf("p1 holds A and B\n");
sem_post(&b);
sem_post(&a);
return NULL;
}
void *p2(void *arg) {
sem_wait(&b); /* opposite order: B first */
sleep(1);
sem_wait(&a);
printf("p2 holds A and B\n");
sem_post(&a);
sem_post(&b);
return NULL;
}
int main(void) {
pthread_t t1, t2;
sem_init(&a, 0, 1);
sem_init(&b, 0, 1);
pthread_create(&t1, NULL, p1, NULL);
pthread_create(&t2, NULL, p2, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}Each thread takes its first semaphore, sleeps, and then blocks on the semaphore the other thread holds. Neither print statement runs.
Following the dotted edges through the holding relationships gives P1 → B → P2 → A → P1. Any cycle in this graph, with one instance per resource, means deadlock.
Fixing the ordering
The standard cure is to impose one global order on all semaphores and require every process to acquire them in that order. A cycle needs some process to hold a later semaphore while waiting for an earlier one, and the rule forbids that. In the program above, change p2 to take a first and b second. The deadlock disappears, and both threads print.
Other approaches have costs:
- Acquire everything at once. This removes hold and wait, but it lowers concurrency and may need an extra semaphore guarding the group acquisition.
- Try-lock with back-off. If the second acquisition fails, release the first and retry. This avoids deadlock but can cause livelock, where both processes keep retrying in step.
- Do not hold a lock while waiting on a condition. This is the producer-consumer rule. Monitors and condition variables enforce it by releasing the monitor lock inside
wait.
Checking a GATE question for deadlock
Questions usually give initial semaphore values and several processes, then ask whether deadlock is possible or what the outputs can be. Use this procedure:
- List which semaphores each process acquires, in order, and which it releases.
- Look for a hold-and-wait pattern: a process that holds one semaphore and then waits on another.
- Build the wait-for relationships, as in the diagram above. A cycle is a candidate deadlock.
- Confirm that some interleaving reaches it. Let each process run exactly up to its first blocking
wait, and check whether all of them stop with nosignalleft to run. - If the semaphores are counting, recompute the values. A cycle is not enough when a counting semaphore has spare units. A deadlock needs every unit to be held by a blocked process.
For example, if A and B are initialised to 2 instead of 1, the opposite-order program no longer deadlocks with two threads, because each wait succeeds. With enough processes to hold all units, the deadlock returns.
Be careful about the word "possible". Deadlock can occur if some interleaving reaches it, even when many interleavings finish normally. A program with a deadlockable ordering is incorrect, not merely unlucky.
Common mistakes
- Assuming that a deadlock needs more than two processes. Two is enough.
- Blaming the semaphore type. Binary and counting semaphores both deadlock when the order is wrong.
- Concluding "no deadlock" because the first interleaving you traced finished. You must consider the interleavings that stop each process at its first blocking point.
- Confusing a lost
signalwith a deadlock. Forgetting asignalleaves processes blocked forever, which looks the same, but the cause is a missing release rather than a cycle.
Exercise
In the bounded-buffer solution, the consumer is changed to call wait(mutex) before wait(full). Initially the buffer is empty (empty = N, full = 0, mutex = 1). Describe an interleaving that deadlocks, and name the circular wait.
Show answer
The consumer runs wait(mutex), so mutex = 0, then wait(full) and blocks because full = 0. The producer produces an item and runs wait(empty), which succeeds, then wait(mutex), which blocks because the consumer holds it. The consumer waits for signal(full), which only the producer sends after it gets mutex. The producer waits for mutex, which only the consumer releases after it gets full. That is a circular wait.
Exercise
Semaphores A, B and C are all initialised to 1. P0 runs wait(A); wait(B). P1 runs wait(B); wait(C). P2 runs wait(C); wait(A). Each process releases both semaphores afterwards. Can the system deadlock? If so, give one change that prevents it.
Show answer
Yes. If each process completes its first wait, P0 holds A, P1 holds B and P2 holds C. Then P0 waits for B, P1 waits for C and P2 waits for A, which is a cycle. Changing P2 to wait(A); wait(C) imposes the global order A, B, C and prevents the cycle.
Exercise
Two threads use semaphores X and Y, both initialised to 2, with the same opposite-order pattern as the A/B program. Is deadlock possible with only these two threads?
Show answer
No. Each semaphore has two units, and each thread needs at most one unit of each. Every wait succeeds, so no thread blocks while another holds the last unit. Deadlock would need enough processes to hold all units of one semaphore while waiting for the other.