Semaphores

Concept

A semaphore is a kernel-managed integer variable used to coordinate access to shared resources among concurrent processes or threads. Two indivisible operations manipulate its value:

OperationConceptual Action
wait (P)Decrease the semaphore value. If it becomes negative, the caller is suspended.
signal (V)Increase the semaphore value. If the new value is non-positive, one suspended caller is resumed.

Atomicity of each operation prevents race conditions on the semaphore itself.

Implementation Styles

StyleCore IdeaWhen a Process Must WaitCPU Cost While WaitingTypical Use Case
Spinlock (busy-waiting)Caller repeatedly tests the semaphore in a tight loop.Spins inside user code or a short kernel loop.Consumes CPU cycles.Ultra-short critical sections on multiprocessors where a context-switch would cost more than the spin.
Blocking (queue-based)Caller is placed on a kernel queue linked to the semaphore.Kernel deschedules the caller (WAITING state).No CPU cycles consumed; context switch cost instead.Longer critical sections or uniprocessor systems where CPU time must be preserved.

Spinlocks favor latency; blocking semaphores favor overall CPU efficiency.

Binary vs Counting Semaphores

TypeInitial RangeMeaning of ValueMain PurposeAnalogy
Binary Semaphore0 or 11 ⇒ resource free, 0 ⇒ resource busyActs like a mutex lock for a single shared resource or critical section.Light switch: on or off.
Counting SemaphoreAny non-negative integerValue = number of identical resource units availableControls access to a pool of interchangeable resources (buffer slots, database connections, etc.).Parking lot counter: slots left.

Binary Semaphore Characteristics

  • Ensures mutual exclusion for one resource.
  • Only the first caller after a signal proceeds; others must wait.

Counting Semaphore Characteristics

  • Allows up to N concurrent accesses where N is the initial value.
  • Becomes binary when initialized to 1.

Functional Roles

ResponsibilityHow a Semaphore Fulfills It
Mutual ExclusionA binary semaphore guards entry and exit of a critical section.
Resource CountingA counting semaphore tracks how many identical resources remain; callers wait when none are free.
Producer–Consumer SynchronizationTwo counting semaphores (empty, full) plus one binary semaphore (mutex) coordinate buffer space and mutual exclusion.
Ordering / SignalingA semaphore initialized to 0 can force one thread to pause until another issues a signal, establishing sequence constraints.

Semaphores thus provide a foundational, hardware-independent mechanism for coordinating concurrent activities in operating systems and multithreaded programs.

Last updated on