What a semaphore is
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.
Two threads may use the shared slots at once, so we create the semaphore with value 2. Read the value as the number of free slots. The 0 in sem_init means threads of one process share it.
Three threads, two slots
T1 calls sem_wait. The value is 2, more than zero, so it drops to 1 and the call returns at once. T1 takes a slot and carries on.
T2 does the same. The value is 1, so it drops to 0 and T2 takes the second slot. Both slots are now in use, and the value 0 says so.
T3 calls sem_wait, but the value is 0 and may not go below zero. So T3 blocks: the kernel puts it to sleep in the queue. A sleeping thread uses no CPU time, unlike a thread spinning in a loop.
T1 is done and calls sem_post. The value goes up from 0 to 1, and because a thread is asleep in the queue, one sleeper, T3, is woken. sem_post never blocks.
T3 wakes inside sem_wait and tries again. Now the value is 1, so it drops to 0 and T3 takes the free slot. At no moment were more than two threads inside.
T2 and T3 post when they finish: the value goes 0, 1, 2. Back at 2 with nobody waiting. The rule held all along: value plus threads inside always equals 2.
Other uses
The same two operations do different jobs. Start at 1 and only one thread fits: a lock, or binary semaphore. Start at 0 and the first wait sleeps until another thread posts: a signal that something happened.
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.