Sub topic 11
Tracing Semaphore Programs and Counting Outcomes
Prerequisites and the tracing model
Assume you know process and thread basics, context switching, preemption, and C-like pseudocode. A semaphore is an integer object accessed only through atomic operations:
wait(S)decreasesSwhenS > 0. IfS == 0, the caller blocks.signal(S)increasesSand may wake one blocked caller.
For tracing, write every possible interleaving of enabled operations. An operation is enabled only when its wait can complete. Do not treat a blocked process as if it continued to its next statement.
A systematic method
Use this process:
- Record the initial semaphore values and shared variables.
- List the next operation for every process.
- Choose one enabled operation and update the state.
- Repeat until every process finishes.
- Record the output or final value for that execution.
- Remove duplicate outcomes when the question asks for distinct results.
For a semaphore with initial value 1, two consecutive wait(S) operations cannot both complete without an intervening signal(S). The semaphore therefore imposes an ordering constraint.
import threading
gate = threading.Semaphore(0)
result = []
def producer():
result.append("A")
gate.release()
def consumer():
gate.acquire()
result.append("B")
p = threading.Thread(target=producer)
c = threading.Thread(target=consumer)
c.start()
p.start()
p.join()
c.join()
print("".join(result))The consumer cannot append "B" until the producer calls release, so the output is always AB, even though the consumer starts first.
Counting possible outcomes
Consider two processes that each execute one operation:
P1: wait(S); print("X"); signal(S)
P2: wait(S); print("Y"); signal(S)If S = 1, either process may acquire the semaphore first. Therefore, the possible outputs are XY and YX.
If a process prints before waiting, that print is not protected:
P1: print("X"); wait(S); signal(S)
P2: print("Y"); wait(S); signal(S)Both XY and YX remain possible, because the scheduler can run either process first.
A useful trace table records only state changes that affect future behavior.
| Step | Operation | `S` | Output |
|---|---|---|---|
| 0 | Initial state | 1 | empty |
| 1 | `P1: wait(S)` | 0 | empty |
| 2 | `P1: print("X")` | 0 | X |
| 3 | `P1: signal(S)` | 1 | X |
After step 3, P2 can complete similarly. A blocked wait does not decrease the semaphore until it eventually succeeds.
Semaphore ordering
Exercise
Exercise
Initially S = 1. P1 executes wait(S), prints 1, signal(S). P2 executes wait(S), prints 2, signal(S). What distinct outputs are possible?
Show answer
12 and 21. Either process may acquire S first, but the two processes cannot print simultaneously because each print occurs while holding the semaphore.