Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You have two problems. The first is that you aren't using <code>while()</code> loops correctly - for example, here:</p> <pre><code>//wait for turn while( pthread_cond_wait(&amp;condA, &amp;mutex) != 0 ) i++; </code></pre> <p>The body of the <code>while</code> loop is the statement <code>i++</code> - this will execute <code>pthread_cond_wait()</code> and <code>i++</code> until the <code>pthread_cond_wait()</code> returns an error, so this is essentially an endless loop.</p> <p>The second is that you can't use a pthreads condition variable on its own - it needs to be paired with some actual shared state (at its simplest, this shared state might just be a flag variable protected by a mutex). The <code>pthread_cond_wait()</code> function is used to wait for the shared state to reach a certain value, and the <code>pthread_cond_signal()</code> function is used when a thread has altered the shared state. Reworking your example to use such a variable:</p> <pre><code>//global variables /* STATE_A = THREAD A runs next, STATE_B = THREAD B runs next */ enum { STATE_A, STATE_B } state = STATE_A; pthread_cond_t condA = PTHREAD_COND_INITIALIZER; pthread_cond_t condB = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *threadA() { int i = 0, rValue, loopNum; while(i&lt;5) { /* Wait for state A */ pthread_mutex_lock(&amp;mutex); while (state != STATE_A) pthread_cond_wait(&amp;condA, &amp;mutex); pthread_mutex_unlock(&amp;mutex); //do stuff for(loopNum = 1; loopNum &lt;= 5; loopNum++) printf("Hello %d\n", loopNum); /* Set state to B and wake up thread B */ pthread_mutex_lock(&amp;mutex); state = STATE_B; pthread_cond_signal(&amp;condB); pthread_mutex_unlock(&amp;mutex); i++; } return 0; } void *threadB() { int n = 0, rValue; while(n&lt;5) { /* Wait for state B */ pthread_mutex_lock(&amp;mutex); while (state != STATE_B) pthread_cond_wait(&amp;condB, &amp;mutex); pthread_mutex_unlock(&amp;mutex); //do stuff printf("Goodbye\n"); /* Set state to A and wake up thread A */ pthread_mutex_lock(&amp;mutex); state = STATE_A; pthread_cond_signal(&amp;condA); pthread_mutex_unlock(&amp;mutex); n++; } return 0; } </code></pre> <p>Note that the use of two condition variables <code>condA</code> and <code>condB</code> is unnecessary here - the code would be just as correct if only one condition variable was used instead.</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