title: c - running 2 threads in parallel with a shared variable
body: <p>Just a beginner to threads, I'm just doing a task which involves these 2 threads.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;pthread.h&gt;
  
  int count = 0;
  
  void waitFor(unsigned int secs)
  {
      unsigned int retTime = time(0) + secs;
      while(time(0) &lt; retTime);
  }
  
  void func1(void * args)
  {
      printf("In func1 ...\n");
      long i = 0;
      while(1){
          i++;
          if(count == 1)
              break;
      }
      printf("The total number counted is: %ld \n", i);
      count = 0;
      i = 0;
  }
  
  void func2(void * args)
  {
      printf("In func2 ...\n");
      waitFor(3);
      count = 1;
  }
  
  
  int main()
  {
      pthread_t th1, th2;
  
      int j = 0;
      while(j++ &lt; 4){
          printf("\nRound:\t%d\n", j);
  
          pthread_create(&amp;th1, NULL, (void*)func1,NULL);
          pthread_create(&amp;th2, NULL, (void*)func2, NULL);
  
          pthread_join(th1,NULL);
          pthread_join(th2,NULL);
          waitFor(3);
      }
  
      return 0;
  }
  </code></pre>
  
  <p>I've read various references and to my understanding pthread_join() means that if there are 2 or more threads, then they will wait for one thread to finish its execution and then next one will start executing and so on.</p>
  
  <p>But when i run this program, the moment pthread_join(th1) is executed, both threads are created and executed 'concurrently'. How is this happening?
  Output:</p>
  
  <pre><code>Round:  1
  In func2 ...
  In func1 ...
  The total number counted is: 897651254 
  
  Round:  2
  In func1 ...
  In func2 ...
  The total number counted is: 1051386065
  
  ........
  </code></pre>
  
  <p>My goal is to run these 2 threads in parallel. For now, join seems to do this; or am I going wrong somewhere?</p>
  
  <p>And I've read that using volatile is not preferred for threads in C. So is there any way I could use count as a signal from thread 2 to 1?</p>