<p>What are the pros / cons of using <code>pthread_cond_wait</code> or using a semaphore ?
I am waiting for a state change like this :</p>

<pre><code>pthread_mutex_lock(&amp;cam-&gt;video_lock);
while(cam-&gt;status == WAIT_DISPLAY) {
    pthread_cond_wait(&amp;cam-&gt;video_cond, &amp;cam-&gt;video_lock);
}
pthread_mutex_unlock(&amp;cam-&gt;video_lock);
</code></pre>

<p>Using a properly initialised semaphore, I think I could do it like this :</p>

<pre><code>while(cam-&gt;status == WAIT_DISPLAY) {
    sem_wait(&amp;some_semaphore);
}
</code></pre>

<p>What are the pros and cons of each method ?</p>

[{'answer_id': 70924, 'author': 'Javier', 'author_id': 11649, 'author_profile': 'https://Stackoverflow.com/users/11649', 'pm_score': 0, 'selected': False, 'text': "<p>In your second snippet, you're getting the lock multitude of times, never releasing it.</p>\n\n<p>In general, the state you're waintin on can be completely expressed by a semaphore, then you can use just that.  A lock structure is smaller in size, and it requires less atomic operations to check/set/release.</p>\n\n<p>Otherwise, if the state is complex, and different parts of the code wait on different conditions of the same variable (eg, here you want x&lt;10; there you want y>x), use cond_wait.</p>\n"}, {'answer_id': 71301, 'author': 'freespace', 'author_id': 8297, 'author_profile': 'https://Stackoverflow.com/users/8297', 'pm_score': 4, 'selected': False, 'text': "<p>Conditionals let you do some things that semaphores won't.</p>\n\n<p>For example, suppose you have some code which requires a mutex, called <code>m</code>. It however needs to wait until some other thread has finish their task, so it waits on a semaphore called <code>s</code>. Now any thread which needs <code>m</code> is blocked from running, even though the thread which has <code>m</code> is waiting on <code>s</code>. These kind of situations can be resolved using conditionals. When you wait on a conditional, the mutex currently held is released, so other threads can acquire the mutex. So back to our example, and suppose conditional <code>c</code> was used instead of <code>s</code>. Our thread now acquires <code>m</code>, and then conditional waits on <code>c</code>. This releases <code>m</code> so other threads can proceed. When <code>c</code> becomes available, <code>m</code> is reacquired, and our original thread can continue merrily along its way.</p>\n\n<p>Conditional variables also allows you to let <em>all</em> threads waiting on a conditional variable to proceed via <code>pthread_cond_broadcast</code>. Additionally it also allows you to perform a <em>timed wait</em> so you don't end up waiting forever.</p>\n\n<p>Of course, sometimes you don't need conditional variables, so depending on your requirements, one or the other may be better. </p>\n"}, {'answer_id': 108918, 'author': 'Steve Jessop', 'author_id': 13005, 'author_profile': 'https://Stackoverflow.com/users/13005', 'pm_score': 7, 'selected': True, 'text': "<p>A semaphore is suited cleanly to a producer-consumer model, although it has other uses. Your program logic is responsible for ensuring that the right number of posts are made for the number of waits. If you post a semaphore and nobody is waiting on it yet, then when they do wait they continue immediately. If your problem is such that it can be explained in terms of the count value of a semaphore, then it should be easy to solve with a semaphore.</p>\n\n<p>A condition variable is a bit more forgiving in some respects. You can for example use cond_broadcast to wake up all waiters, without the producer knowing how many there are. And if you cond_signal a condvar with nobody waiting on it then nothing happens. This is good if you don't know whether there's going to be a listener interested. It is also why the listener should always check the state with the mutex held before waiting - if they don't then they can miss a signal and not wake up until the next one (which could be never).</p>\n\n<p>So a condition variable is suitable for notifying interested parties that state has changed: you acquire the mutex, change the state, signal (or broadcast) the condvar and release the mutex. If this describes your problem you're in condvar territory. If different listeners are interested in different states you can just broadcast and they'll each in turn wake up, figure out whether they've found the state they want, and if not wait again.</p>\n\n<p>It's very gnarly indeed to attempt this sort of thing with a mutex and a semaphore. The problem comes when you want to take the mutex, check some state, then wait on the semaphore for changes. Unless you can atomically release the mutex and wait on the semaphore (which in pthreads you can't), you end up waiting on the semaphore while holding the mutex. This blocks the mutex, meaning that others can't take it to make the change you care about. So you will be tempted to add another mutex in a way which depends on your specific requirements. And maybe another semaphore. The result is generally incorrect code with harmful race conditions.</p>\n\n<p>Condition variables escape this problem, because calling cond_wait automatically releases the mutex, freeing it for use by others. The mutex is regained before cond_wait returns.</p>\n\n<p>IIRC it is possible to implement a kind of condvar using only semaphores, but if the mutex you're implementing to go with the condvar is required to have trylock, then it's a serious head-scratcher, and timed waits are out. Not recommended. So don't assume that anything you can do with a condvar can be done with semaphores. Plus of course mutexes can have nice behaviours that semaphores lack, principally priority-inversion avoidance.</p>\n"}, {'answer_id': 434872, 'author': 'Blaisorblade', 'author_id': 53974, 'author_profile': 'https://Stackoverflow.com/users/53974', 'pm_score': 3, 'selected': False, 'text': '<p>The 2nd snippet is racy, don\'t do that.</p>\n\n<p>The other answers have a nice discussion of the relative merits; I\'ll just add that <code>pthread_cond_broadcast</code> is a clear advantage of condition variables.</p>\n\n<p>Beyond that, I\'m just more used to condition variables for that, as they are what you use in Java, even because they help you to avoid races when checking the shared flags.</p>\n\n<p>Indeed, in the 2nd snippet you don\'t have any lock protecting the read of cam->status, so it is accessed through a data race. Most platforms will let you get away with that in this particular example, but that has undefined semantics, by POSIX and by the memory model of the next C/C++ standards.</p>\n\n<p>In fact, a real race condition is possible if another thread allocates a new cam structure and overwrites cam; the waiting thread might see the update to the \'cam\' pointer without seeing the initialization of cam->status. Indeed, the 2nd snippet is asking for trouble, in this case and in general.</p>\n\n<p><a href="http://www.hpl.hp.com/personal/Hans_Boehm/c++mm/" rel="noreferrer">http://www.hpl.hp.com/personal/Hans_Boehm/c++mm/</a></p>\n'}, {'answer_id': 71291384, 'author': 'Abhishek Sagar', 'author_id': 756120, 'author_profile': 'https://Stackoverflow.com/users/756120', 'pm_score': 0, 'selected': False, 'text': '<pre><code>while(cam-&gt;status == WAIT_DISPLAY) {\n    sem_wait(&amp;some_semaphore);\n}\n</code></pre>\n<p>This is completely wrong. This is prone to race condition. By the time the thread blocks on sem_Wait, the condition cam-&gt;status == WAIT_DISPLAY may not hold good in the system as some other thread may have modified it. So, your thread is now sleeping for all wrong reasons.</p>\n'}]
['https://Stackoverflow.com/questions/70773', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11589/']