title: How to make a thread wait for other threads to finish
body: <p>I have a program where I created two threads. In one thread I assigned a value to integers <code>a</code> and <code>b</code>. In the second thread, I want to access <code>a</code> and <code>b</code>, to change their values.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;pthread.h&gt;
  
  struct data {
      int a;
      int b;
  };
  
  struct data temp;
  
  void *assign(void *temp)
  {
      struct data *new;
  
      new = (struct data *) temp;
      new-&gt;a = 2;
      new-&gt;b = 2;
      printf("You are now in thread1..\n The value of a and b is: %d, %d", new-&gt;a + 1, new-&gt;b + 1);
      printf("\n");
      pthread_exit(NULL);
  }
  
  void *add(void *temp1)
  {
      struct data *new1;
      new1 = (struct data *) temp1;
      printf("You are now in thread 2\nValue of a and b is: %d, %d\n", new1-&gt;a - 1, new1-&gt;b - 1);
      pthread_exit(NULL);
  }
  
  int main()
  {
      pthread_t threads[2];
      pthread_attr_t attr;
      void *status;
      int rc, t;
      pthread_attr_init(&amp;attr);
      pthread_attr_setdetachstate(&amp;attr, PTHREAD_CREATE_JOINABLE);
      pthread_create(&amp;threads[0], NULL, assign, (void *) &amp;temp);
      pthread_create(&amp;threads[1], NULL, add, (void *) &amp;temp);
      pthread_attr_destroy(&amp;attr);
      for (t = 0; t &lt; 2; t++) {
          rc = pthread_join(threads[t], &amp;status);
          if (rc) {
              printf("ERROR; return code from pthread_join() is %d\n", rc);
              exit(-1);
          }
          printf("Main: completed join with thread %ld having a status of %ld\n", t, (long) status);
      }
      pthread_exit(NULL);
      return 0;
  }
  </code></pre>
  
  <p>But the above program executes the two threads simultaneously. Sometimes I get</p>
  
  <pre><code>thread1..
  The value of a and b is: 3, 3
  thread 2
  Value of a and b is: 1, 1
  </code></pre>
  
  <p>and sometimes I get</p>
  
  <pre><code>thread 2
  Value of a and b is: -1, -1
  You are now in thread1..
  The value of a and b is: 3, 3
  </code></pre>
  
  <p>I want to make thread-2(add) to wait for thread-1(assign) to finish and exit. How can I implement it?</p>