When a thread is created detached (PTHREAD_CREATE_DETACHED), its thread ID and other resources can be reused as soon as the thread terminates. Use pthread_attr_setdetachstate(3THR) when the calling thread does not want to wait for the thread to terminate.
When a thread is created nondetached (PTHREAD_CREATE_JOINABLE), it is assumed that you will be waiting for it. That is, it is assumed that you will be executing a pthread_join(3T)() on the thread.
Whether a thread is created detached or nondetached, the process does not exit until all threads have exited. See "Finishing Up" for a discussion of process termination caused by premature exit from main().
Prototype: int pthread_attr_setdetachstate(pthread_attr_t *tattr,int detachstate);
#include <pthread.h> pthread_attr_t tattr; int ret; /* set the thread detach state */ ret = pthread_attr_setdetachstate(&tattr,PTHREAD_CREATE_DETACHED);
When there is no explicit synchronization to prevent it, a newly created, detached thread can die and have its thread ID reassigned to another new thread before its creator returns from pthread_create().
For nondetached (PTHREAD_CREATE_JOINABLE) threads, it is very important that some thread join with it after it terminates--otherwise the resources of that thread are not released for use by new threads. This commonly results in a memory leak. So when you do not want a thread to be joined, create it as a detached thread.
#include <pthread.h> pthread_attr_t tattr; pthread_t tid; void *start_routine; void arg int ret; /* initialized with default attributes */ ret = pthread_attr_init()(&tattr); ret = pthread_attr_setdetachstate()(&tattr,PTHREAD_CREATE_DETACHED); ret = pthread_create()(&tid, &tattr, start_routine, arg);
pthread_attr_setdetachstate() returns zero after completing successfully. Any other returned value indicates that an error occurred. If the following condition occurs, the function fails and returns the corresponding value.