EMZETT.
Login

Semaphore

In short: A semaphore is a counter that controls how many threads may access a limited resource at once. A mutex is the special case with value 1.

In more detail: Before access the counter is decreased (acquire/wait). If it is zero, the thread waits. After access it is increased (release/signal) and a waiting thread may continue.

In Depth

  • Example: At most 5 simultaneous database connections: semaphore with initial value 5.
  • Binary semaphore: Value 0 or 1, resembles a mutex. The difference: a semaphore may be released by a different thread.
  • Producer-consumer: One semaphore counts free slots, another counts filled entries in the buffer.
  • Dangers: A forgotten release blocks forever, wrong order leads to deadlock.
  • Languages: Semaphore in Java, threading.Semaphore in Python, in Go usually a buffered channel.

See also: Mutex (mutual exclusion), Deadlock