WAIT QUEUESLOT 1SLOT 2slots1sem_init(&slots, 0, 2);2sem_wait(&slots);3/* use a slot */4sem_post(&slots);STARTT1T2T3zZ
Back: the wait queue and the two slotsMiddle: the semaphore, its number = free slots · front: the code and the threadsDiscs: threads T1, T2, T3; zz marks a sleeping threadAt the back, the wait queue and a room with two slots. In the middle, the semaphore: its number is the count of free slots. In front, the code each thread runs and the bench where threads T1, T2 and T3 start. T1 and T2 pass the semaphore and take the slots (2 to 1 to 0). T3 finds 0 and sleeps in the queue. T1's post raises the number to 1 and wakes T3, which takes the free slot. When everyone posts, the number is back to 2. Which sleeper is woken depends on the system: POSIX leaves it to the scheduling policy (with SCHED_FIFO, the highest-priority thread that has waited longest), and Python says the order should not be relied on. With one sleeper, as here, there is no choice.

What a semaphore is

  1. A semaphore is a whole number that never goes below zero, plus a queue of sleeping threads. It has two operations: wait takes one away, and post adds one back. Each runs atomically, as one step no other thread can split.

Three threads, two slots

Other uses

What happens

;; step 1/9 · idea
semaphore   value  >= 0     (never negative in POSIX)
            queue  of sleeping threads

wait   P, down, sem_wait   value > 0 ? value - 1 : sleep
post   V, up,   sem_post   value + 1, wake one sleeper

P and V are Dijkstra's names (Dutch words).
both are atomic: two threads never see a half-done update

POSIX and Python semaphores never go below zero. OSTEP's version, after Dijkstra, lets the value go negative: then minus the value is the number of sleeping threads. Both behave the same for the threads. Between being woken and taking the value, another thread could call sem_wait first and win the slot. The woken thread then simply sleeps again. Semaphores promise the count, not who gets each slot.