Semaphore: A lock with a counter
(IRL: A flag that transmits a signal over a long distance)
- Contains: An atomic integer V, A queue of waiting threads
- init: Create a semaphore with an initial V
- wait (decrement): If V ≤ 0, block. Otherwise decrease V by 1
- signal (increment): Increase V by 1, unblock any waiting thread
Why semaphore?
- Some synchronization problems make more sense with semaphores.
- Multiple threads can call wait and signal
Types
Binary Semaphore: Count = 0/1, sem_init(1)
- Single access to a resource, mutex, same as lock
Counting Semaphore: sem_init(N > 1)
- N resources available, multiple threads can pass
Limitations
- Waiting reason is hidden in
sem_wait
sem_wait
only checks count != 0
, more complex conditions require CVs