Detaching Threads

Name:
pthread_detach()
System call or function: Function Links: Online Manual | Course Packet
What it does: detaches a thread
thread
: the thread is no longer joinable, so there is no need to join it. A detached thread automatically releases its resources upon exit from the thread's function.
What libraries you must include:
#include <pthread.h> // Defines pthread_detach().
Syntax:
int pthread_detach (pthread_t thread);
Description of arguments:
thread
: pointer to a
pthread_t
variable that was used for calling
pthread_create()
.
What type it returns:
int
On success:
0
On failure: a non-zero error number that
errno
is usually set to.
If failure, does it set
errno
?
No
Quick example:
if ((result = pthread_detach (thread)) != 0) /* error */
Other variations: N/A

Rule of thumb: your program must call either

pthread_join()
or
pthread_detach()
(but not both) on every thread that you create with
pthread_create()
!

Otherwise, if a thread isn't joined nor detached, it will release it resources only after the process exits.