Implement a counting semaphore using a mutex and a condition variable.
#include <pthread.h>
typedef struct {
pthread_mutex_t m;
pthread_cond_t cv;
unsigned count;
} csem_t;
void csem_init(csem_t *s, unsigned initial)
{
pthread_mutex_init(&s->m, NULL);
pthread_cond_init(&s->cv, NULL);
s->count = initial;
}
void csem_wait(csem_t *s) /* P / down */
{
pthread_mutex_lock(&s->m);
while (s->count == 0) /* while, not if: spurious wake-ups */
pthread_cond_wait(&s->cv, &s->m);
s->count--;
pthread_mutex_unlock(&s->m);
}
void csem_post(csem_t *s) /* V / up */
{
pthread_mutex_lock(&s->m);
s->count++;
pthread_cond_signal(&s->cv); /* wake one waiter */
pthread_mutex_unlock(&s->m);
}
Points: the mutex protects the count; the condition variable lets waiters sleep until the count is positive; the while loop handles spurious wake-ups and other threads taking the unit first. Unlike POSIX sem_post, this version is not async-signal-safe (it locks a mutex), so it cannot be posted from a signal handler or ISR.