1. LPU MCA Semester 1
  2. CAP366
  3. Unit 5

CAP366 · Unit 5: Process synchronization

Semaphores

16 practice questions · in the MTE and ETE syllabus

Key points

  • wait decrements and may block; signal increments and may wake
  • Binary = mutex, counting = n instances
  • Bounded buffer: mutex 1, empty N, full 0
  • Wrong wait order can deadlock

A semaphore S is an integer accessed only through atomic wait(S) (decrement; block if it becomes negative) and signal(S) (increment; wake a waiter if S <= 0). A binary semaphore (0/1) works as a mutex; a counting semaphore tracks a number of resource instances.

Trace: S = 2; A, B, C call wait: S = 1, 0, -1 and C blocks. A signal then wakes C and S returns to 0.

Bounded buffer: mutex = 1, empty = N, full = 0. Producer: wait(empty), wait(mutex), add, signal(mutex), signal(full). Consumer mirrors it.

MistakeConsequence
wait(mutex) before wait(empty) in the producer when fullDeadlock (holds mutex while blocked)
signal(mutex) ... wait(mutex) swappedMutual exclusion lost
P1: A then B, P2: B then APossible deadlock

Exam pitfall: the order of the two waits matters; waiting on mutex first can deadlock, whereas the order of the two signals does not.

Try two questions

Question 1 · Tier 2, Understand

A spinlock is a lock in which:

  1. The lock is released automatically by the kernel after a fixed time-out
  2. A waiting process sleeps on a queue and is woken when the lock is released
  3. A waiting process loops (busy-waits) until the lock becomes available
  4. The lock may be held by several processes at once, so none of them has to wait
Show the answer

C. Spinlocks avoid context-switch cost but waste CPU cycles; useful for very short critical sections.

Question 2 · Tier 1, Recall

Which pair of operations is defined on a semaphore?

  1. fork (F) and join (J)
  2. wait (P) and signal (V)
  3. request (Q) and grant (G)
  4. open (O) and close (C)
Show the answer

B. wait(S) decrements S (blocks if S would become negative); signal(S) increments S.