/ˈsɛm.ə.fɔːr/
noun — “the OS’s polite traffic cop for your processes.”
Semaphore is a synchronization primitive used by operating systems and concurrent programs to control access to shared resources and prevent conflicts like race conditions. It acts as a signaling mechanism, allowing processes or threads to coordinate their actions safely without stepping on each other’s toes.
In computing, Semaphores are typically implemented as integer counters with atomic operations. The two basic operations are wait (often called P or down) and signal (V or up). When a process performs a wait, the counter is decremented. If the result is negative, the process blocks until another process performs a signal to increment the counter and release it. This simple mechanism enforces controlled access to critical sections and shared resources.
Semaphore comes in two flavors: binary and counting. A binary Semaphore acts like a simple lock (0 or 1), ensuring mutual exclusion for a single resource. A counting Semaphore can manage access to a finite number of identical resources, allowing multiple processes to proceed concurrently up to the defined limit. These mechanisms integrate with Process Management and Context Switch operations to maintain orderly execution.
Semaphores are foundational for building higher-level synchronization constructs such as mutexes, monitors, and barriers. They are widely used in operating systems, multithreaded applications, and even real-time environments where predictable coordination is crucial. By using Semaphores, developers can prevent deadlocks, race conditions, and other concurrency hazards that can arise in multitasking systems.
In practice, Semaphores are often combined with other Resource Limits and signaling mechanisms to build robust, fault-tolerant applications. For instance, they might control access to a pool of database connections or manage concurrent I/O operations to an I/O Stream.
Conceptually, a Semaphore is like a parking lot gate: it only lets in as many cars (processes) as there are spaces, and the gatekeeper ensures no chaos occurs. Processes that arrive when the lot is full wait patiently until a spot opens.
Semaphore is like giving your processes tiny glow sticks — green means go, red means hold it right there.
See Mutex, Critical Section, Deadlock, Process Management, Context Switch.