Understanding semaphores with pthreads (code included)
<p>So in class, we learned about semaphores and stuff and our professor let us know that this code below would be handy to learn for our exam. Unfortunately our exam is on Friday, and <em>whole list of excuses</em>, i just need to be able to understand this code for the exam and for future cases. I understand that the mutex_t is a lock system and the cond_t is a condition system in which signals get passed through sema_P and sema_V (if the value is 0, race condition occurs and the thread is locked out by cond_wait until another thread increases the value and is unlocked by cond_signal), but why does a lock need to get passed around? Why is there a mutex_lock and mutex_unlock in both decrementer P() and incrementer V()? How does this work with the threads and the conditions (cont_t)?</p>

<pre><code>typedef struct
{
        pthread_mutex_t lock;
        pthread_cond_t wait;
        int value;
} sema;

void pthread_sema_init(sema *s, int count)
{
        s-&gt;value = count;
        pthread_cond_init(&amp;(s-&gt;wait),NULL);
        pthread_mutex_init(&amp;(s-&gt;lock),NULL);
        return;
}

void pthread_sema_P(sema *s)
{
        pthread_mutex_lock(&amp;(s-&gt;lock));
        s-&gt;value--;
        if(s-&gt;value &lt; 0) {
                pthread_cond_wait(&amp;(s-&gt;wait),&amp;(s-&gt;lock));
        }
        pthread_mutex_unlock(&amp;(s-&gt;lock));
        return;
}

void pthread_sema_V(sema *s)
{

        pthread_mutex_lock(&amp;(s-&gt;lock));
        s-&gt;value++;
        if(s-&gt;value &lt;= 0) {
                pthread_cond_signal(&amp;(s-&gt;wait));
        }
        pthread_mutex_unlock(&amp;(s-&gt;lock));
}
</code></pre>