Semaphore
Updated 2026-07-28
Summary
A semaphore is a synchronization object that maintains a count between zero and a specified maximum. When a thread performs a wait operation on the semaphore, the count is decremented by one; when a thread performs a release operation, the count is incremented by one. When the count is zero, threads waiting on the semaphore will not succeed until the semaphore becomes signaled.
Definition
A semaphore is a synchronization object that maintains a count between zero and a specified maximum. When a thread performs a wait operation on the semaphore, the count is decremented by one; when a thread performs a release operation, the count is incremented by one. When the count is zero, threads waiting on the semaphore will not succeed until the semaphore becomes signaled. If the count is greater than zero, the semaphore is in a signaled state; if the count equals zero, it is in a nonsignaled state. The concept of the semaphore was invented by Dutch computer scientist Edsger W. Dijkstra and is widely used in various operating systems. In a system, each process is given a semaphore representing its current state; processes that do not have control are forced to stop at specific points and wait for a signal to proceed.
Introduction
How to use
A semaphore is a synchronization object that maintains a count between zero and a specified maximum. When a thread performs a wait operation on the semaphore, the count is decremented by one; when a thread performs a release operation, the count is incremented by one. When the count is zero, threads waiting on the semaphore will not succeed until the semaphore becomes signaled.
Mechanism
Proposed by Dijkstra, it is a counter protected by atomic operations: P (wait, decrement by 1, if <0 then block), V (signal, increment by 1, if there are waiters then wake). Used for mutual exclusion (binary semaphore = lock) and counting resources (N-valued semaphore controls concurrency). The core is "safely coordinating access under contention".
Practice
In progress 0/4Practice this model in one real situation:
Cases
- Database connection pool throttling; team "only do 3 projects at a time"; printer queue; rate-limiting gateway (similar to token bucket).
Common pitfalls
- Forgetting to release after acquisition causes permanent blocking; acquiring multiple semaphores in arbitrary order leads to deadlock; treating semaphore as an ordinary counter and modifying it arbitrarily.
Sources
Source support: Explicit
References currently contain only Wikipedia links; primary sources still need review.
- zh.wikipedia.orghttps://zh.wikipedia.org/wiki/%E4%BF%A1%E5%8F%B7%E9%87%8Fverified
account_treeGenealogyexpand_more
PRIVATE NOTES · Only visible to you
SAVED Q&A
ENTRY Q&A · Private saving available
Ask with a clear boundary
thinkingmodels answers from published entry context only.
Your question is sent to thinkingmodels. The answer uses public entry context only.
RELATED MODELS