title: pthread_cond_wait for 2 threads
body: <p>I'm trying to implement <code>pthread_cond_wait</code> for 2 threads. My test code is trying to use two threads to preform the following scenario:</p>
  
  <ul>
  <li>Thread B waits for condition</li>
  <li>Thread A prints "Hello" five times</li>
  <li>Thread A signals thread B</li>
  <li>Thread A waits</li>
  <li>Thread B prints "Goodbye"</li>
  <li>Thread B signals thread A</li>
  <li>Loop to start (x5)</li>
  </ul>
  
  <p>So far the code prints "Hello" five times and then gets stuck. From examples I've looked at it seems I'm on the right track, "Lock mutex, wait, get signaled by other thread, unlock mutex, do stuff, loop"</p>
  
  <p>Test Code:</p>
  
  <pre><code>//Import 
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;pthread.h&gt;
  #include &lt;unistd.h&gt;
  
  //global variables
  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)
      {
          //unlock mutex
          rValue = pthread_mutex_unlock(&amp;mutex);
  
          //do stuff
          for(loopNum = 1; loopNum &lt;= 5; loopNum++)
              printf("Hello %d\n", loopNum);
  
          //signal condition of thread b
          rValue = pthread_cond_signal(&amp;condB);
  
          //lock mutex
          rValue = pthread_mutex_lock(&amp;mutex);
  
          //wait for turn
          while( pthread_cond_wait(&amp;condA, &amp;mutex) != 0 )
  
          i++;
      }
  
  }
  
  
  
  void *threadB()
  {
      int n = 0, rValue;
  
      while(n&lt;5)
      {
          //lock mutex
          rValue = pthread_mutex_lock(&amp;mutex);
  
          //wait for turn
          while( pthread_cond_wait(&amp;condB, &amp;mutex) != 0 )
  
          //unlock mutex
          rValue = pthread_mutex_unlock(&amp;mutex);
  
          //do stuff
          printf("Goodbye");
  
          //signal condition a
          rValue = pthread_cond_signal(&amp;condA);
  
          n++;        
      }
  }
  
  
  
  
  int main(int argc, char *argv[])
  {
      //create our threads
      pthread_t a, b;
  
      pthread_create(&amp;a, NULL, threadA, NULL);
      pthread_create(&amp;b, NULL, threadB, NULL);
  
      pthread_join(a, NULL);
      pthread_join(b,NULL);
  }
  </code></pre>
  
  <p>A pointer in the right direction would be greatly appreciated, thanks!
  (Code compiled on Linux using "gcc timeTest.c -o timeTest -lpthread")</p>