title: How to create 2 threads and to print Thread id's alternatively and numbers from 1 to 20?
body: <p>Code</p>
  
  <pre><code>#include &lt;pthread.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  pthread_t tid[2];
  void* fun(void* ptr) 
  {
      int i = *((int *) ptr);
      int self_id;
      self_id=pthread_self();
      printf("Thread %u  ",self_id);
      printf("printing %d \n", i);
      pthread_exit(NULL);
      return NULL;
  }
  
  int main() 
  {
      int i=0,j=1,k;
      for(j=1;j&lt;21;)
      {
          for(i=0;i&lt;2;i++)
          {   
              pthread_create(&amp;tid[i],NULL,fun,&amp;j);
              sleep(1);
              j++;
          }
  
      }
      for(j=1;j&lt;21;)
      {
          for(i=0;i&lt;2;i++)
          {
              pthread_join(tid[i],NULL);
              j++;
          }
      }
          pthread_exit(NULL);
  }
  </code></pre>
  
  <p>So if the 2 threads are t1 and t2 and their thread id's are say 1023 and 1024, then the output should be as</p>
  
  <pre><code>            Thread 1023 printing 1
              Thread 1024 printing 2
              Thread 1023 printing 3
              Thread 1024 printing 4
  
              and so on till printing 20
  </code></pre>
  
  <p>But the output of my code is</p>
  
  <pre><code>            Thread 1023 printing 1
              Thread 1024 printing 2
              Thread 1025 printing 3
              Thread 1026 printing 4
  
              and so on till printing 20
  </code></pre>
  
  <p>The thread id's are not alternating. How to make the thread id's alternate.</p>