title: When to use pthread_exit() and when to use pthread_join() in Linux?
body: <p>I am new to pthreads, and I am trying to understand it. I saw some examples like the following. </p>
  
  <p>I could see that the <code>main()</code> is blocked by the API <code>pthread_exit()</code>, and I have seen examples where the main function is blocked by the API <code>pthread_join()</code>. I am not able to understand when to use what? </p>
  
  <p>I am referring to the following site - <a href="https://computing.llnl.gov/tutorials/pthreads/" rel="noreferrer">https://computing.llnl.gov/tutorials/pthreads/</a>. I am not able to get the concept of when to use <code>pthread_join()</code> and when to use <code>pthread_exit()</code>. </p>
  
  <p>Can somebody please explain? Also, a good tutorial link for pthreads will be appreciated.</p>
  
  <pre><code>#include &lt;pthread.h&gt;
  #include &lt;stdio.h&gt;
  #define NUM_THREADS     5
  
  void *PrintHello(void *threadid)
  {
     long tid;
     tid = (long)threadid;
     printf("Hello World! It's me, thread #%ld!\n", tid);
     pthread_exit(NULL);
  }
  
  int main (int argc, char *argv[])
  {
     pthread_t threads[NUM_THREADS];
     int rc;
     long t;
     for(t=0; t&lt;NUM_THREADS; t++){
        printf("In main: creating thread %ld\n", t);
        rc = pthread_create(&amp;threads[t], NULL, PrintHello, (void *)t);
        if (rc){
           printf("ERROR; return code from pthread_create() is %d\n", rc);
           exit(-1);
        }
     }
  
     /* Last thing that main() should do */
     pthread_exit(NULL);
  </code></pre>
  
  <p>Realized one more thing i.e.  </p>
  
  <pre><code>pthread_cancel(thread);
  pthread_join(thread, NULL);
  </code></pre>
  
  <p>Sometimes, you want to cancel the thread while it is executing.
  You could do this using pthread_cancel(thread);.
  However, remember that you need to enable pthread cancel support.
  Also, a clean up code upon cancellation.</p>
  
  <pre><code>thread_cleanup_push(my_thread_cleanup_handler, resources);
  pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
  
  static void my_thread_cleanup_handler(void *arg)
  {
    // free
    // close, fclose
  }
  </code></pre>