Synchronization: Mutex & Semaphores

When threads share data, a critical section must be protected to avoid race conditions. Mutexes and semaphores are the main tools.

Cheat sheet

  • ▸Race condition: result depends on the order of thread execution.
  • ▸Critical section solution needs: Mutual Exclusion, Progress, Bounded Waiting.
  • ▸Mutex: lock owned by one thread; only the owner unlocks.
  • ▸Semaphore: integer with wait(P) and signal(V); counting or binary.
  • ▸Classic problems: Producer–Consumer, Readers–Writers, Dining Philosophers.
  • ▸Peterson's solution: software 2-process mutual exclusion.

Mutex vs Semaphore

AspectMutexSemaphore
TypeLocking mechanismSignalling mechanism
ValueLocked / unlockedInteger ≥ 0
OwnershipOwner must releaseAny thread can signal
UseProtect one resourceCount N resources / ordering

Visual

wait(S):   while S <= 0 ; S--
signal(S): S++
Producer: wait(empty) wait(mutex) put signal(mutex) signal(full)

Top 10 campus interview questions

Quick quiz

1. Which is NOT a requirement for critical section?

2. In producer–consumer, initial value of 'empty' for buffer size N:

3. Who can release a mutex?

4. Priority inheritance solves:

5. Semaphore S=3. After 5 wait() calls, how many threads are blocked?