{
  "id": "semaphore-computing",
  "title": "Semaphore (computing)",
  "lang": "en",
  "source_lang": "en",
  "summary": "A semaphore is a synchronization primitive that uses an atomic permit counter to coordinate concurrent execution and control access to shared resources.",
  "category": "computer-science",
  "subcategory": "software",
  "type": "concept",
  "aliases": [
    "Counting semaphore",
    "semaphore synchronization primitive"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/semaphore-computing/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/semaphore-computing/",
      "json": "https://aiwiki.page/zh/semaphore-computing.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "A semaphore is a synchronization primitive used in concurrent computing to coordinate execution and regulate access to resources. It maintains a logical count of available permits and provides operations that acquire or release them atomically. An acquisition proceeds when a permit is available; otherwise, the caller waits or receives a failure result, depending on the operation used. Semaphores can limit the number of simultaneous users of a resource, enforce ordering between activities, and communicate that work or capacity has become available."
    },
    {
      "heading": "Origins and terminology",
      "text": "Edsger W. Dijkstra introduced semaphores in the 1960s as part of his work on cooperating sequential processes. They became a foundational mechanism in operating systems and the study of concurrent programs.\n\nThe original operations are conventionally written P and V, names derived from Dutch terminology. Modern interfaces commonly use names such as:\n\nPurpose | Common operation names\nAcquire a permit, waiting if necessary | wait, acquire, down, P\nRelease a permit | post, release, up, V\nAttempt acquisition without waiting | try_wait, try_acquire\nAcquire subject to a deadline or timeout | timed_wait, try_acquire_for, try_acquire_until\n\nThe exact return values, interruption rules, maximum counts, and scheduling guarantees depend on the interface."
    },
    {
      "heading": "Abstract behavior",
      "text": "A semaphore is initialized with a count \\(k \\geq 0\\). Its two essential operations are:\n\n- Acquire: If a permit is available, consume one and continue. If none is available, wait until acquisition becomes possible.\n- Release: Add a permit, allowing a waiting participant to proceed if one is present.\n\nThese changes must behave as atomic operations: concurrent callers cannot both acquire the same permit, and a release must not be lost through a race between checking availability and entering a waiting state.\n\nIn a common nonnegative-count model, the abstract transitions are:\n\n\\[\\operatorname{acquire}(S):\\quad S>0 \\implies S\\leftarrow S-1\\]\n\n\\[\\operatorname{release}(S):\\quad S\\leftarrow S+1\\]\n\nWhen \\(S=0\\), acquisition waits rather than performing the decrement immediately. These expressions specify behavior, not an implementation: an ordinary comparison followed by an ordinary decrement would not provide the required atomicity.\n\nSome textbook formulations instead decrement first and allow a negative internal count to represent waiting participants. This is a different representation of waiting, not a requirement that public semaphore interfaces expose negative values.\n\nPermits and ownership\n\nA semaphore generally does not associate a permit with a particular owner. One thread or process can acquire a permit and another can release it. This enables producer–consumer signaling, but also means that an erroneous release can create an extra permit.\n\nFor resource management, a semaphore initialized to \\(k\\) permits can enforce:\n\n\\[0 \\leq H \\leq k,\\]\n\nwhere \\(H\\) is the number of outstanding acquisitions. This bound depends on the program pairing each successful acquisition with exactly one release and not releasing permits it never acquired. Initialization alone does not make an ordinary counting semaphore detect such mistakes."
    },
    {
      "heading": "Principal types",
      "text": "Counting semaphore\n\nA counting semaphore represents an arbitrary nonnegative number of permits, subject to implementation limits. Initializing it to \\(k\\) permits allows at most \\(k\\) simultaneous acquisitions before further callers must wait.\n\nTypical uses include limiting access to a fixed-size connection pool, tracking free buffer slots, and counting queued work items.\n\nBinary semaphore\n\nA binary semaphore has at most one available permit. It can represent exclusive availability or a pending notification.\n\nA binary semaphore is not necessarily equivalent to a counting semaphore merely initialized to one. If an ordinary counting semaphore receives extra releases, its count may exceed one. A binary semaphore interface restricts the state to zero or one, but the handling of an extra release varies: it may be rejected, have no additional effect, or violate the interface's usage requirements.\n\nBounded semaphore\n\nA bounded semaphore enforces a configured upper limit, commonly the initial resource capacity. Releasing beyond that limit is treated as an error in interfaces that provide this feature. Bounded semaphores can expose mismatched acquire–release operations that an ordinary counting semaphore might silently accept.\n\nBinary and bounded semaphore terminology is not completely uniform across libraries."
    },
    {
      "heading": "Common coordination patterns",
      "text": "Limiting concurrent access\n\nA semaphore initialized to \\(k\\) can limit an operation to \\(k\\) concurrent participants:\n\nslots = Semaphore(k)\n\nuse_resource():\n    slots.acquire()\n    try:\n        perform_operation()\n    finally:\n        slots.release()\n\nThe cleanup construct ensures that a successful acquisition is followed by a release even if perform_operation exits through an exception. The semaphore limits participation but does not select or identify an individual resource. A pool of distinct connections or devices usually also requires a protected structure that assigns them.\n\nSignaling completion or availability\n\nA semaphore initialized to zero can communicate from one activity to another:\n\nready = Semaphore(0)\n\nproducer():\n    prepare_result()\n    ready.release()\n\nconsumer():\n    ready.acquire()\n    use_result()\n\nIf the producer releases before the consumer starts waiting, the permit remains available. This retained notification is a defining feature of semaphore signaling.\n\nRepeated releases can accumulate multiple permits in a counting semaphore, but the semaphore does not contain the associated data. A queue or other storage mechanism is needed if each permit corresponds to a distinct item.\n\nBounded producer–consumer buffer\n\nA bounded buffer with capacity \\(N\\) commonly uses:\n\n- empty, initialized to \\(N\\), to count unused positions;\n- full, initialized to zero, to count available items;\n- a mutex to protect modifications to the buffer.\n\nproduce(item):\n    empty.acquire()\n    lock(buffer_mutex)\n    enqueue(item)\n    unlock(buffer_mutex)\n    full.release()\n\nconsume():\n    full.acquire()\n    lock(buffer_mutex)\n    item = dequeue()\n    unlock(buffer_mutex)\n    empty.release()\n    return item\n\nThe counting semaphores track capacity and availability; the mutex protects the buffer's internal state. Waiting for empty or full before taking the mutex prevents a participant from holding the buffer lock while waiting for another participant to change the buffer.\n\nThis is conceptual pseudocode. Production implementations also need to account for exceptions, cancellation, and shutdown."
    },
    {
      "heading": "Relationship to other synchronization primitives",
      "text": "Mutexes and mutual exclusion\n\nA mutex principally provides mutual exclusion for a critical section. It normally has ownership: the participant that locks it is responsible for unlocking it. Semaphore permits generally have no such ownership.\n\nA binary semaphore can enforce exclusive entry under a suitable protocol, but it does not automatically inherit mutex features such as ownership checking, recursive locking, or priority inheritance. Conversely, a mutex is generally unsuitable for a protocol in which one thread acquires and another releases.\n\nCondition variables\n\nA condition variable allows a thread to wait for a predicate over shared state, normally while cooperating with a mutex. Waiting atomically releases that mutex and reacquires it before returning.\n\nA semaphore instead maintains permits. A release can remain available for a later acquisition, whereas a condition-variable notification is not generally retained for a future waiter. Condition-variable programs therefore test their predicate in a loop rather than treating a notification as a stored resource.\n\nAsynchronous semaphores\n\nIn asynchronous programming, a semaphore can suspend a task or coroutine without blocking its underlying operating-system thread. Such semaphores are useful for limiting concurrent requests or background jobs.\n\nTheir scope and guarantees differ from those of thread-oriented or process-shared semaphores. An asynchronous semaphore may coordinate tasks within one runtime without being safe for arbitrary use across operating-system threads."
    },
    {
      "heading": "Implementation and memory visibility",
      "text": "A semaphore implementation must coordinate permit accounting with waiting and wake-up. Implementations commonly combine atomic instructions, an internal lock, and a queue of waiters. Some handle uncontended operations entirely in user space and involve the kernel only when blocking or waking is necessary.\n\nBlocking avoids continuously occupying a processor while waiting, although some implementations spin briefly when a permit is expected to become available soon. Performance depends on contention, scheduling, wake-up costs, and the duration of the protected work.\n\nCorrect synchronization also involves memory visibility. Under a language or library's memory model, a release and a corresponding successful acquisition commonly establish an ordering that makes preceding writes visible to the acquiring participant. The precise guarantee belongs to the API specification, not merely to the presence of an integer counter.\n\nSemaphores may operate between threads in one process or between processes using supported interprocess communication facilities. Process-shared use requires appropriate initialization and storage; placing an ordinary thread-local semaphore object in shared memory is not sufficient by itself."
    },
    {
      "heading": "Correctness, fairness, and limitations",
      "text": "Semaphores are low-level primitives, and correct local operations do not by themselves make a larger protocol correct.\n\n- Deadlock: Participants can enter deadlock by acquiring semaphores in conflicting orders, holding a lock while waiting for an action that requires that lock, or attempting to reacquire an exhausted non-reentrant permit.\n- Permit leaks: A successful acquisition without a matching release can permanently reduce capacity.\n- Excess releases: An unmatched release can permit more simultaneous access than intended.\n- Starvation: Some participants may wait indefinitely while others repeatedly acquire permits. First-in, first-out admission is not a universal semaphore guarantee.\n- Priority inversion: A high-priority participant can wait for progress that depends on a lower-priority participant. Ownerless semaphore designs complicate the ownership-based remedies available for some mutexes.\n- Cancellation and interruption: A timed-out or cancelled wait must not accidentally consume a permit. If cancellation occurs after acquisition, cleanup must account for the acquired permit.\n- Races involving inspection: Reading the current count does not reserve a permit. Another participant may change it immediately, so testing the count before acquiring is not a substitute for atomic acquisition.\n\nA semaphore also does not protect unrelated data automatically. Incorrect access outside the agreed protocol can still produce a race condition."
    },
    {
      "heading": "Interfaces and applications",
      "text": "POSIX defines semaphore interfaces including sem_wait, sem_trywait, sem_timedwait, and sem_post, with named and unnamed forms. Microsoft Windows provides kernel semaphore objects. Language libraries also expose semaphores; C++20, for example, includes std::counting_semaphore and std::binary_semaphore.\n\nSemaphores are used in worker coordination, bounded queues, resource pools, device access, and admission control. A semaphore that limits outstanding requests controls concurrency, not necessarily request rate: if requests finish quickly, a fixed number of permits can support a high number of requests per second.\n\nThe basic abstraction assumes reliable shared semaphore state. Extending permit control across independently failing machines introduces additional questions—such as expired holders, lost communication, and stale clients—that require protocols beyond a local semaphore."
    }
  ],
  "links": [
    "synchronization-computing",
    "concurrent-computing",
    "operating-system",
    "atomic-operation",
    "thread-computing",
    "process-computing",
    "mutex",
    "pseudocode",
    "mutual-exclusion",
    "critical-section",
    "condition-variable",
    "asynchronous-programming",
    "coroutine",
    "kernel-operating-system",
    "memory-model",
    "interprocess-communication",
    "deadlock",
    "race-condition",
    "posix",
    "microsoft-windows"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}