Semaphore¶
Category: Synchronization · Status: stub · Lessons: chapter 04, Waiting for each other (planned)
One line: A counter of permits: taking one waits while none are left, and returning one lets a waiter in — a lock that up to n tasks may hold at once.
Also called: counting semaphore, binary semaphore.
How it connects¶
flowchart LR
n_semaphore["Semaphore"]
n_synchronization["Synchronization"]
n_semaphore -->|is a| n_synchronization
classDef center stroke-width:3px
class n_semaphore center
classDef outside stroke-dasharray: 4 3
class n_synchronization outside
- Is a kind of: Synchronization
- See also: Buffered and bounded channels, Classic synchronization problems, Concurrency primitives, Latch
In each language¶
| Rust | None in std::sync ↗; tokio::sync::Semaphore ↗ is fair, giving permits out in the order they were requested |
| Go | None in sync: a buffered channel serves as a counting semaphore, and golang.org/x/sync/semaphore ↗ provides a weighted one |
| C | None in C11 <threads.h> ↗; POSIX sem_t fills the gap |
| C++ | std::counting_semaphore and std::binary_semaphore ↗ (C++20) |
| Java | Semaphore ↗ with an optional fairness setting, which the untimed tryAcquire ignores |
| Python | threading.Semaphore ↗, and BoundedSemaphore, which checks that it is not released too many times |
| C# | SemaphoreSlim ↗; blocked threads enter in no guaranteed order |
| Kotlin | Semaphore ↗ in kotlinx.coroutines, fair and FIFO |
| The operating system | POSIX sem_wait ↗ and sem_post ↗ |
Where to read more¶
- In a sibling library: Go: A buffered channel as a semaphore ↗
- In the books: Learn Concurrent Programming with Go, James Cutajar — ch. 5, 'Condition variables and semaphores'
- In the books: Multi-Threaded Programming in C++, Mark Walmsley — ch. 5, 'Semaphores'
- In the books: The Little Book of Semaphores, Allen B. Downey — ch. 2, 'Semaphores'
- In the books: Rust Atomics and Locks, Mara Bos — ch. 10, 'Ideas and Inspiration' → 'Semaphore'
- In the books: Pro Asynchronous Programming with .NET, Richard Blewett, Andrew Clymer — ch. 4, 'Basic Thread Safety' → 'A Semaphore Out of the Box'
- In the books: Python Concurrency with asyncio, Matthew Fowler — ch. 11, 'Synchronization' → 'Limiting concurrency with semaphores'
- Notes: Semaphores in general - semaphore ↗
- Reference: Wikipedia: Semaphore (programming) ↗
- Reference: Allen B. Downey: The Little Book of Semaphores ↗