- 2075 Baisakh · 5 marks
Semaphore for mutual exclusion
Short answer
A binary semaphore initialized to 1 enforces mutual exclusion by placing wait(mutex) before and signal(mutex) after the critical section. The first process executing wait decrements the semaphore to 0 and enters; others block until the owner signals. For example, P1: wait(mutex); balance+=100; signal(mutex); P2: wait(mutex); balance-=50; signal(mutex);
How can semaphore be used to enforce mutual exclusion? Give a suitable example.
A semaphore is an integer variable with two atomic operations, wait(S) (down/P) and signal(S) (up/V). Initialising a binary semaphore mutex = 1 and surrounding every critical section with wait and signal enforces mutual exclusion.
wait(S): while (S <= 0) ; S-- (or block if S == 0)
signal(S): S++ (or wake a blocked process)
Method
semaphore mutex = 1; /* shared, initial value 1 */
Process Pi:
do {
wait(mutex); /* entry section */
/* critical section */
signal(mutex); /* exit section */
/* remainder section */
} while (TRUE);
Why it works
- mutex = 1 means the critical section is free. The first process executing
waitmakes it 0 and enters. - Any other process executing
waitfinds 0 and blocks (it is queued, not spinning). - When the owner executes
signal, one blocked process is woken and enters; if none waits, mutex returns to 1. - So at most one process is in the critical section at a time.
Example
Two processes P1 and P2 update a shared bank balance:
P1: wait(mutex); balance = balance + 100; signal(mutex);
P2: wait(mutex); balance = balance - 50; signal(mutex);
If P1 enters first (mutex becomes 0), P2 blocks at wait until P1 signals, so the updates occur one after the other and the final balance is always correct.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Critical section; mutual exclusion · Operating System, chapter 3
- Race condition; mutual exclusion requirements · Operating System, chapter 3
- Producer-consumer using semaphore · Operating System, chapter 3 · asked 2×
- Producer-consumer: semaphore and messages · Operating System, chapter 3
- pipe(); semaphore in distributed systems · Operating System, chapter 3
- TSL; semaphore operations as class · Operating System, chapter 3
- Token ring mutual exclusion · Distributed System, chapter 6 · asked 3×
- Ricart-Agrawala mutual exclusion · Distributed System, chapter 6 · asked 2×
- Lamport algorithm for mutual exclusion · Distributed System, chapter 6
- Mutual exclusion via sleep and wake · Embedded System, chapter 6