How to Implement Semaphores
Let's see how we can make a semaphore out of a lock and a condition variable.
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.
Press + to interact
typedef struct __Zem_t {int value;pthread_cond_t cond;pthread_mutex_t lock;} Zem_t;// only one thread can call thisvoid 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 ...