liveBook · Manning

Semaphore

As explained in The Coder Cafe

A semaphore is a synchronization mechanism maintaining a counter that limits or coordinates concurrent access to a resource.

A semaphore is a synchronization mechanism that maintains a counter to limit or coordinate concurrent access to a pool of shared resources. Unlike a mutex, it can allow several threads to proceed at once, up to a configured limit. section 2.3 section 2.0

A semaphore coordinates access through a repeating acquire-and-release operation:

  • A thread checks the counter before using a resource. section 2.3
  • If the count is greater than zero, the thread proceeds and decrements the count. section 2.3
  • When the thread finishes, it increments the count, signaling that a resource is available again. section 2.3
  • When the count reaches zero, additional threads must wait rather than exceed the resource capacity. section 2.3

A parking lot with limited spaces

A parking lot with five spaces represents a semaphore initialized with a count of five. Each arriving car takes a space and reduces the count; when the lot is full, further cars wait. When a car leaves, the count increases and another car can enter. section 2.3

A mutex protects one resource or critical section through exclusive ownership. A semaphore instead signals availability, permits multiple simultaneous users up to its limit, and has no strict requirement that the thread changing the count be the one that acquired a resource. section 2.3 section 2.5

How The Coder Cafe covers it

How deep it goes
Explains counters, decrement-and-increment signaling, capacity limits, and mutex contrasts, but does not provide implementation code.
Examples
Uses a five-space parking lot to model resource capacity, waiting, acquisition, and release.
What it assumes
Assumes basic concurrency and shared-resource concepts while distinguishing semaphores from mutexes.
What you can do after
Operate/configure bounded concurrent access by tracking available resources and signaling releases.
How it connects
Connects semaphores to concurrency, parallelism, coroutines, mutexes, shared resources, data races, and race conditions.

Also explained in

Compare how 6 books explain semaphore →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Coder Cafe. The section links point to the parts of the book it draws on.