Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your <code>anotherThread</code> simply calls <code>pthread_cond_wait</code> without first testing whether the desired condition (counter reaching ten) has already happened. This is incorrect logic, which will lead to the <em>lost wakeup problem</em>: the name of a recurring bug that plagues incorrectly written multithreaded programs.</p> <p>Condition variables are stateless. If <code>pthread_cond_signal</code> or <code>pthread_cond_broadcast</code> is called on a condition on which no threads are currently waiting, the operation has no effect. It is not remembered. So it is possible for your signaling thread to count to <code>10</code> very quickly, and signal the condition variable, before the other thread has reached the <code>pthread_cond_wait</code> call.</p> <p>You need a loop around <code>pthread_cond_wait</code>. The condition must be checked in case it is already true, so that the thread does not wait for a wakeup which already happened. And it should be a loop because wakeups can be spurious: just because the thread falls through the <code>pthread_cond_wait</code> doesn't mean that the condition is actually true:</p> <pre><code>while (cont &lt; 10) pthread_cond_wait(&amp;cond, &amp;myMutex); </code></pre> <p>Also, there is no need to create a thread attribute just to make a thread joinable. This is the default situation when you use a null pointer for the creation attribute. POSIX threads are joinable unless created detached, or converted to detached with <code>pthread_detach</code>.</p> <p>Another thing: whenever possible, avoid calling <code>pthread_cond_signal</code> while holding a mutex lock. It's not incorrect, but it's potentially wasteful, because the operation may actually have to call into the OS kernel to wake up a thread, and so you're holding this expensive mutex lock over the entire system call (when all you really need it for is protecting a few machine instructions that working with shared data in your application).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload