Semaphores
A semaphore is a counter that threads wait on and post to. wait decrements when the count is positive, or sleeps until it can. post increments and wakes a waiter.
Detailed Explanation
Dijkstra's semaphore is older than pthreads. POSIX provides unnamed semaphores (sem_init, sem_wait, sem_post, sem_destroy) and named ones that live in the filesystem (sem_open). A mutex is a binary lock with an owner. A semaphore is a count without an owner: any thread may post.
A semaphore initialized to 1 can stand in for a mutex, and then you lose the "same thread unlocks" check and the condvar pairing. Prefer a mutex for mutual exclusion. Use a semaphore when the count is the resource: N identical worker slots, a producer/consumer buffer with empty and filled counts, a notification that does not need a separate ready flag.
sem_wait is the P operation and can fail with EINTR if a signal arrives. A careful loop retries. sem_trywait returns immediately with EAGAIN if the count is zero. sem_timedwait takes an absolute deadline.
macOS deprecated unnamed semaphores (sem_init returns -1). Named semaphores or dispatch semaphores are the replacement there. Linux implements both. Portable code often wraps the primitive or uses a mutex plus a count plus a condvar, which is the same idea under a different API and works everywhere pthreads does.
Process-shared semaphores (pshared != 0) live in shared memory and coordinate processes, not just threads. That is a different lifetime and permission story. Do not turn pshared on by accident.
Starvation and barging depend on the implementation. A semaphore does not promise FIFO. If you need fairness, document it or use a queue of waiters you control.
Code Examples
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
static sem_t go;
static void *worker(void *arg)
{
(void)arg;
sem_wait(&go);
printf("released\n"); /* prints: released */
return NULL;
}
int main(void)
{
if (sem_init(&go, 0, 0) != 0) { /* count 0: wait blocks */
perror("sem_init");
return 1;
}
pthread_t t;
pthread_create(&t, NULL, worker, NULL);
sem_post(&go);
pthread_join(t, NULL);
sem_destroy(&go);
return 0;
}Common Gotchas
`sem_init` is unreliable on macOS
check the return, and use a named semaphore or a condvar wrapper if you must ship there.
`sem_wait` can return `-1` with `EINTR`
retry, do not treat it as a permanent failure.
A semaphore has no owner
a `post` from a thread that never `wait`ed is normal. That is also how a missing `wait` turns into an unbounded count.
`sem_destroy` while threads are waiting is undefined
wake and join first.