Sub topic 11
Tracing Semaphore Programs and Counting Outcomes
This chapter assumes you know the wait and signal operations on binary and counting semaphores. It also assumes you can read C-like pseudocode and know that the scheduler may switch processes between any two statements. The goal is a repeatable procedure for answering GATE-style questions of the form "what can this program print?", "what is the final value of S?" and "can it deadlock?".
The rules you trace with
Use one convention throughout a trace and state it.
wait(S): if S > 0, decrement S and continue. If S = 0, the caller blocks and joins S's waiting queue.signal(S): if some process is waiting on S, wake one of them. The woken process finishes itswait, and S stays unchanged. Otherwise S is incremented.
Some textbooks use the other convention, where wait always decrements and a negative S means that |S| processes are blocked. Both conventions give the same behaviour. They differ only in what number you write down while processes are blocked.
A signal with no waiter is remembered, because it increments S. This is the main difference from a condition variable, where a signal with no waiter is lost.
The counting invariant
When no process is blocked on S, the value is:
S = initial + (signals executed) − (waits completed)
A wait that has blocked has not completed, so it does not count. This formula answers most "final value" questions without any interleaving.
A systematic trace
- List every process as a sequence of statements and mark its program counter.
- Write the current value of each semaphore and each waiting queue.
- At each step, pick any process that is not blocked and execute its next statement.
- When a
signalwakes a process, move that process to runnable. - Stop when all processes finish. If every unfinished process is blocked, you have found a deadlock.
Different choices at step 3 produce different outcomes. Counting outcomes means counting the distinct results across all legal choices.
Worked trace: forcing the order 1, 2, 3
Three processes share two semaphores, both initialised to 0.
semaphore s12 = 0, s23 = 0;
void P1(void) { print(1); signal(s12); }
void P2(void) { wait(s12); print(2); signal(s23); }
void P3(void) { wait(s23); print(3); }Take the worst-looking schedule, where P3 runs first.
| Step | Action | s12 | s23 | Blocked |
|---|---|---|---|---|
| 0 | start | 0 | 0 | none |
| 1 | P3 executes `wait(s23)` | 0 | 0 | P3 |
| 2 | P2 executes `wait(s12)` | 0 | 0 | P3, P2 |
| 3 | P1 prints 1 | 0 | 0 | P3, P2 |
| 4 | P1 executes `signal(s12)`, waking P2 | 0 | 0 | P3 |
| 5 | P2 prints 2 | 0 | 0 | P3 |
| 6 | P2 executes `signal(s23)`, waking P3 | 0 | 0 | none |
| 7 | P3 prints 3 | 0 | 0 | none |
Every schedule gives the same output. You can check this on a real machine with POSIX semaphores. Compile with gcc -pthread.
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
sem_t s12, s23;
void *p1(void *arg) { printf("1\n"); sem_post(&s12); return NULL; }
void *p2(void *arg) { sem_wait(&s12); printf("2\n"); sem_post(&s23); return NULL; }
void *p3(void *arg) { sem_wait(&s23); printf("3\n"); return NULL; }
int main(void) {
pthread_t t[3];
sem_init(&s12, 0, 0);
sem_init(&s23, 0, 0);
pthread_create(&t[2], NULL, p3, NULL);
pthread_create(&t[1], NULL, p2, NULL);
pthread_create(&t[0], NULL, p1, NULL);
for (int i = 0; i < 3; i++) pthread_join(t[i], NULL);
return 0;
}Counting possible outputs
A semaphore adds precedence constraints to the program. For example, signal(s) in one process followed by wait(s) in another forces everything before the signal to happen before everything after the wait. The set of possible outputs is the set of orderings that respect those constraints and each process's own statement order.
| Program | Constraint | Possible outputs |
|---|---|---|
| Three processes each do `wait(S); print(i); signal(S)` with S = 1 | none between them, only mutual exclusion | 6 (all permutations of 1, 2, 3) |
| The chain above | 1 before 2 before 3 | 1 |
| P1: print A, `signal(S)`. P2: `wait(S)`, print B. P3: print C. S = 0 | A before B | 3 (ABC, ACB, CAB) |
The first row shows that mutual exclusion does not impose an order. A semaphore initialised to 1 used as a lock allows every serial order of the critical sections.
Count the third row by placing C into the fixed sequence A, B. C can go before A, between them, or after B, which gives three positions.
Counting semaphores and limits
A counting semaphore initialised to N lets N processes pass. Consider this program with S = 2 and five processes:
semaphore S = 2;
void worker(void) {
wait(S);
/* region R */
signal(S);
}At most 2 processes are inside region R at once. The value of S is 2 minus the number of processes currently inside. If region R updates a shared variable, two processes can still race there, so this is not mutual exclusion. Mutual exclusion needs an initial value of 1.
Deadlock in a trace
semaphore a = 0, b = 0;
void P(void) { wait(a); signal(b); }
void Q(void) { wait(b); signal(a); }Both processes block at their first statement. Each is waiting for a signal that only the other can send, and neither can reach it. You do not need to try other schedules. Because the first statement of each process is a wait on a semaphore at 0, no other schedule exists. The trace has one state and it is stuck.
Common errors
- Counting a blocked
waitas completed when you apply the final-value formula. A blocked process has not decremented anything under the non-negative convention. - Assuming statements in different processes execute in the order written on the page. Only the order within one process, plus semaphore constraints, is guaranteed.
- Forgetting that a
signalbefore the matchingwaitis not lost. The wait later finds S = 1 and passes. - Treating a multi-statement block between
waitandsignalas atomic when the semaphore has an initial value above 1. - Stopping the trace at the first completed schedule. For "can" questions you need one schedule that produces the result. For "must" questions you need an argument that no schedule avoids it.
Exercises
Exercise
S = 0. P1 runs print(A); signal(S). P2 runs wait(S); print(B). P3 runs print(C). How many different outputs are possible, and what are they?
Show answer
Three outputs. A must precede B because P2 cannot pass wait(S) until P1 signals. C is independent and can appear before A, between A and B, or after B. The outputs are CAB, ACB and ABC.
Exercise
A semaphore starts at 3. Over a run, 7 wait operations complete and 5 signal operations execute, and no process is blocked at the end. What is the final value, and what does the value tell you about the run?
Show answer
3 + 5 − 7 = 1. The value never went below 0 only if the run was legal, so at most 3 waits could complete before the first signal. The final value 1 means one more wait would pass without blocking.
Exercise
Two semaphores X = 1 and Y = 0. P1 runs wait(X); wait(Y); print(1). P2 runs wait(X); print(2); signal(Y). Can the system deadlock? Explain with a schedule.
Show answer
Yes. If P1 runs first, it takes X (X = 0) and then blocks on wait(Y) because Y = 0. P2 then blocks on wait(X), because P1 holds X and will never release it. P2 would have been the one to signal Y, so neither process can proceed. If P2 runs first, it prints 2, signals Y and no deadlock occurs, so the outcome depends on the schedule.