title: Understanding Pthreads
body: <p>I came across a concept in <strong>Advanced Linux Programming</strong>. Here's <a href="http://www.cse.hcmut.edu.vn/~hungnq/courses/nap/alp.pdf">a link</a>: refer to <strong>4.5 GNU/Linux Thread Implementation</strong>.</p>
  
  <p>I'm clear with the concept what author say's, but I'm confused with the program he has explained for printing processID's for threads.</p>
  
  <p>Here is the code</p>
  
  <pre><code>#include &lt;pthread.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  void* thread_function (void* arg)
  {
      fprintf (stderr, "child thread pid is %d\n", (int) getpid ());
      /* Spin forever. */
      while (1);
      return NULL; 
  }
  
  int main ()
  {
      pthread_t thread;
      fprintf (stderr, "main thread pid is %d\n", (int) getpid ());
      pthread_create (&amp;thread, NULL, &amp;thread_function, NULL);
      /* Spin forever. */
      while (1);
      return 0;
  } 
  </code></pre>
  
  <p>The output for the above code according to author is</p>
  
  <pre><code>% cc thread-pid.c -o thread-pid -lpthread
  % ./thread-pid &amp;
  [1] 14608
  main thread pid is 14608
  child thread pid is 14610 
  </code></pre>
  
  <p>The output I get when I compile is</p>
  
  <pre><code>[1] 3106
  main thread pid is 3106
  child thread pid is 3106
  </code></pre>
  
  <p>I understand that to create a thread, linux internally calls <strong>clone</strong>(most of the cases), same as <strong>fork</strong> system call does to create a process. The only difference is thread created in process share the same process address space, while process created by a parent process copies the parent process address space. So, what I think is printing process ID in threads result in the same processID. but, its not the same result in book.</p>
  
  <p>Please tellme what is he talking about..? Is the answer wrong in the book/mine..?</p>