Posix Detached Vs Joinable threads

By default when we create a posix thread , it is in joinable mode. There is another thread’s mode that is Detached. So a thread can be either Joinable or Detached.

To create a thread in detach state, we set the detachstate thread attribute with the function pthread_attr_setdetachstate() to PTHREAD_CREATE_DETACHED.

  • pthread_join is called from another thread (usually the thread that created it) to wait for a thread to terminate and obtain its return value.¬† Let us see below example and its output.
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>

void *foo( void *arg)
{
   printf("Running ...foo\n");
   sleep(3);
   pthread_exit( (void*)400);
}

int main()
{
  int i=0;
  int res;

  pthread_t tid;

  res = pthread_create(&tid,NULL,foo,NULL);
  if( res )
  {
     printf("thread creation fails\n");
     exit(-1);
  }

  // wait for tid to finish  
  pthread_join(tid,(void **)&i);


  printf("%d\n",i);

  return 0;
}
  • In the above program pthread_join make calling thread suspend until the thread tid finishes. So when the thread tid would finish its execution and terminates , then only after that main thread will print value of i , that would be 400.
  • pthread_detach can be called from either the thread itself or another thread, and indicates that you don’t want the thread’s return value or the ability to wait for it to finish.
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>

void *foo( void *arg)
{
   pthread_detach(pthread_self());
   printf("Running ...foo\n");
   sleep(3);
   pthread_exit( (void*)42);
}

int main()
{
  int i=0;
  int res;

  pthread_t tid;

  res = pthread_create(&tid,NULL,foo,NULL);
  if( res )
  {
     printf("threadcreation fails\n");
     exit(-1);
  }
  printf("%d\n",i);
  // sleep main thread for 2 s
  sleep(2);
  return 0;
}

Note: In the above program the thread tid would not make main thread to wait  for thread tid to finish.

  • A Detached thread automatically releases it allocated resources on exit while Joinable threads must need to call pthread_join to release allocated resources.
  • pthread_detach() will return non zero value in case of error.
  • pthread_join blocks the calling thread while pthread_detach does not.

 

Ref: https://stackoverflow.com/questions/22427007/difference-between-pthread-exit-pthread-join-and-pthread-detach



Related Contents to follow