Skip to main content

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 wait makes it 0 and enters.
  • Any other process executing wait finds 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)

All Operating System chapter 3 questions →