Search⌘ K

How to Implement Semaphores

Explore how to implement semaphores by combining locks and condition variables. Understand the design choices in building semaphores, study the code closely, and gain insights into common challenges when using semaphores for synchronization.

We'll cover the following...

Finally, let’s use our low-level synchronization primitives, locks, and condition variables, to build our own version of semaphores called … (drum roll here) … Zemaphores. This task is fairly straightforward, as you can see in the code snippet below.

C
typedef struct __Zem_t {
int value;
pthread_cond_t cond;
pthread_mutex_t lock;
} Zem_t;
// only one thread can call this
void Zem_init(Zem_t *s, int value) {
s->value = value;
Cond_init(&s->cond);
Mutex_init(&s->lock);
}
void Zem_wait(Zem_t *s) {
Mutex_lock(&s->lock);
while (s->value <= 0)
Cond_wait(&s->cond, &s->lock);
s->value--;
Mutex_unlock(&s->lock);
}
void Zem_post(Zem_t *s) {
Mutex_lock(&s->lock);
s->value++;
Cond_signal(&s->cond);
Mutex_unlock(&s->lock);
}

Explanation

In the code above, we use just one lock and one ...