title: Pthread conditional signal - not working as expected
body: <p>I am working on a project and trying to use  <code>pthread_cond_wait()</code> and  <code>pthread_cond_signal()</code> to  synchronize two threads.</p>
  
  <p>My code looks something like this:</p>
  
  <pre><code>pthread_mutex_t lock_it = PTHREAD_MUTEX_INITIALIZER;
  pthread_cond_t write_it = PTHREAD_COND_INITIALIZER;
  
     int main(int argc, char**argv)
    {
  
       pthread_t t_send_segments, t_recv_acks;
  
       pthread_create(&amp;t_send_segments, NULL, send_segments, (void*)NULL);
       pthread_create(&amp;t_recv_acks,     NULL, recv_acks,     (void*)NULL);
  
       pthread_join(t_recv_acks, (void**)NULL);
  
       pthread_mutex_destroy(&amp;lock_it);
       pthread_cond_destroy(&amp;write_it);
  }
  
   void* send_segments(void *v) {
      for(;;) {
         pthread_mutex_lock(&amp;lock_it);
         printf("s1\n");
         printf("s2\n");
         pthread_cond_wait(&amp;write_it, &amp;lock_it);
         printf("s3\n");
         printf("s4\n");
         printf("s5\n"); 
         pthread_mutex_unlock(&amp;lock_it);
      }
      return 0;
   }
  
   void* recv_acks(void *v) {
      for(;;) {
         pthread_mutex_lock(&amp;lock_it);
         printf("r1\n");
         pthread_cond_signal(&amp;write_it);
         printf("r2\n");
         pthread_mutex_unlock(&amp;lock_it);
      }  
      return 0;
   }
  </code></pre>
  
  <p>The expected output is:</p>
  
  <pre><code>s1
  s2
  r1
  s3
  s4
  s5
  s1
  s2
  r2
  r1
  s3
  s4
  s5
  
  (etc)
  </code></pre>
  
  <p>My output doesn't follow this pattern at all. Clearly I have a logic error somewhere, but I'm not understanding where. Why doesn't the <code>recv_acks()</code> thread <em>always</em> yield when it hits the <code>pthread_cond_signal()</code> - since the <code>pthread_cond_wait()</code> always executes first (because of the order in which I create the threads) and the <code>cond_wait()</code> always executes since its in the critical section?</p>