pthread_detach() — Detach a thread
Standards
Standards / Extensions | C or C++ | Dependencies |
---|---|---|
POSIX.4a
Single UNIX Specification, Version 3 |
both | POSIX(ON)
|
Format
#define _OPEN_THREADS
#include <pthread.h>
int pthread_detach(pthread_t *thread);
SUSV3:
#define _UNIX03_THREADS
#include <pthread.h>
int pthread_detach(pthread_t thread);
General description
Allows storage for the thread whose thread ID is in the location thread to be reclaimed when that thread ends. This storage is reclaimed on process exit, regardless of whether the thread was detached, and may include storage for thread's return value. If thread has not ended, pthread_detach() will not cause it to end.
pthread_t is the data type used to uniquely identify a thread. It is returned by pthread_create() and used by the application in function calls that require a thread identifier.
Returned value
If successful, pthread_detach() returns 0.
If unsuccessful, pthread_detach() returns -1 and
sets errno to one of the following values:
- Error Code
- Description
- EINVAL
- The value specified by thread is not valid.
- ESRCH
- A value specified by thread refers to a thread that is already detached.
Special behavior for Single UNIX Specification, Version 3: If unsuccessful, pthread_detach() returns an error number to indicate the error.
Example
CELEBP28
/* CELEBP28 */
#define _OPEN_SYS
#define _OPEN_THREADS
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
void *thread(void *arg) {
char *ret;
printf("thread() entered with argument '%s'\n", arg);
if ((ret = (char*) malloc(20)) == NULL) {
perror("malloc() error");
exit(2);
}
strcpy(ret, "This is a test");
pthread_exit(ret);
}
main() {
pthread_t thid;
void *ret;
if (pthread_create(&thid, NULL, thread, "thread 1") != 0) {
perror("pthread_create() error");
exit(1);
}
if (pthread_join_d4_np(thid, &ret) != 0) {
perror("pthread_create() error");
exit(3);
}
printf("thread exited with '%s'\n", ret);
if (pthread_detach(&thid) != 0) {
perror("pthread_detach() error");
exit(4);
}
}
Output:
thread() entered with argument 'thread 1'
thread exited with 'This is a test'