pthread_attr_setdetachstate() — Set the detach state attribute
Standards
Standards / Extensions | C or C++ | Dependencies |
---|---|---|
POSIX.4a |
both | POSIX(ON) |
Format
#define _OPEN_THREADS
#include <pthread.h>
int pthread_attr_setdetachstate(pthread_attr_t *attr, int *detachstate);
SUSV3:
#define _UNIX03_THREADS
#include <pthread.h>
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);
General description
Alters the
current detachstate setting of a thread
attributes object, which can be set to PTHREAD_CREATE_JOINABLE or PTHREAD_CREATE_DETACHED.
- 0
- Causes all the threads created with attr to be in an undetached state. An undetached thread will keep its resources after termination.
- 1
- Causes all the threads created with attr to be in a detached state. A detached thread will have its resources automatically freed by the system at termination. Thus, you cannot get the thread's termination status, or wait for the thread to terminate by using pthread_join().
You can use a thread attribute object to manage the characteristics of threads in your application. It defines the set of values to be used for the thread during its creation. By establishing a thread attribute object, you can create many threads with the same set of characteristics, without defining those characteristics for each thread. You can define more than one thread attribute object.
Returned value
If successful, pthread_attr_setdetachstate() returns 0.
If unsuccessful, pthread_attr_setdetachstate() returns -1.
- Error Code
- Description
- EINVAL
- The value of detachstate was not valid or the value specified by attr does not refer to an initialized thread attribute object.
Special behavior for Single UNIX Specification, Version 3: If unsuccessful, pthread_attr_setdetachstate() returns an error number to indicate the error.
Example
CELEBP11
/* CELEBP11 */
#define _OPEN_THREADS
#include <stdio.h>
#include <pthread.h>
void **stat;
void *thread1(void *arg)
{
printf("hello from the thread\n");
pthread_exit((void *)0);
}
int main()
{
int ds, rc;
size_t s1;
pthread_attr_t attr;
pthread_t thid;
rc = pthread_attr_init(&attr);
if (rc == -1) {
perror("error in pthread_attr_init");
exit(1);
}
ds = 0;
rc = pthread_attr_setdetachstate(&attr, &ds);
if (rc == -1) {
perror("error in pthread_attr_setdetachstate");
exit(2);
}
rc = pthread_create(&thid, &attr, thread1, NULL);
if (rc == -1) {
perror("error in pthread_create");
exit(3);
}
rc = pthread_join(thid, stat);
exit(0);
}