title: pthread_join doesn't work
body: <p>What I want to accomplish:</p>
  
  <p>In the main function are created two threads. They increment a global variable with the number 5. And send a signal to consumer thread that decrements the variables.In the consumer thread between each decrementation the current value is displayed. The main thread has to wait until all the threads are finished and then exit.</p>
  
  <p>What I get:</p>
  
  <p>Some times the main function exits before the consumer had a chance to display the results. I'm using pthread_join, but it returns error code 3.</p>
  
  <p>Any Ideas how to get the wanted results?</p>
  
  <p>The code is bellow.</p>
  
  <pre><code>#include &lt;pthread.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;errno.h&gt;
  
  static pthread_mutex_t mtx;
  static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
  
  void *producer(void *arg);
  void *consumer(void *arg);
  static int avail = 0;
  
  int main(int argc, char *argv[]){
  
      pthread_t cons1, prod1, prod2;
  
      int status;
      int t1;
      int t2;
      int t3;
  
      pthread_attr_t attr;
      pthread_attr_init(&amp;attr);
      pthread_attr_setdetachstate(&amp;attr, PTHREAD_CREATE_JOINABLE);
  
      pthread_mutexattr_t mtxAttr;
      pthread_mutexattr_settype(&amp;mtxAttr, PTHREAD_MUTEX_ERRORCHECK);
      pthread_mutex_init(&amp;mtx, &amp;mtxAttr);
  
      t1 = pthread_create(&amp;prod1, &amp;attr, producer, NULL);
      if(t1 != 0){
      perror("problem1");
      }
      t2 = pthread_create(&amp;prod2, &amp;attr, producer, NULL);
      if(t2 != 0){
      perror("problem2");
      }
      t3 = pthread_create(&amp;cons1, &amp;attr, consumer, NULL);
      if(t3 != 0){
      perror("problem3");
      }
  
      status = pthread_join(t1, NULL);
      if(status != 0){
      perror("can't join1");
      }
  
      status = pthread_join(t2, NULL);
      if(status != 0){
      perror("can't join2");
      printf("\n%d\n", status);
      }
      status = pthread_join(t3, NULL);
      if(status != 0){
      printf("%s",strerror(errno));
      }
      printf("\nend result \t%d\n",avail);
      printf("fin\n");
      //while(1){}
      return 0;
  }
  
  void *producer(void *arg){
      int s;
      printf("producer\n");
      s = pthread_mutex_lock(&amp;mtx);
      avail+=5;
      s = pthread_mutex_unlock(&amp;mtx);
      s = pthread_cond_signal(&amp;cond);
      pthread_exit(NULL);
  }
  
  void *consumer(void *arg){
      int s;
      while(1) {
      s = pthread_mutex_lock(&amp;mtx);
      if(s !=0 ){
          perror("lock err");
      }
      while (avail == 0) {
          s = pthread_cond_wait(&amp;cond, &amp;mtx);
      }
      while (avail &gt; 0) {
          avail--;
          printf("Temp: %d \n",avail);
      }
  
      s = pthread_mutex_unlock(&amp;mtx);
      }
      printf("done");
      pthread_exit(NULL);
  }
  </code></pre>