Skip to content

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

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