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.

  • 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.

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