Linux 线程属性初始化,销毁,设置和获得分离属性

线程属性初始化和销毁

#include <pthread.h>
int pthread_attr_init(pthread_attr_t *attr);
int pthread_attr_destroy(pthread_attr_t *attr);

在pthread_create函数的第二个参数就是线程属性.

线程属性结构

设置和获得线程的分离属性

#include <pthread.h>
int pthread_attr_setdetachstate(pthread_attr_t attr, int detachstate);
int pthread_attr_getdetachstate(const pthread_attr_t
attr, int *detachstate);
On success, these functions return 0; on error, they return a nonzero error number.

PTHREAD_CREATE_DETACHED
PTHREAD_CREATE_JOINABLE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>

void out_state(pthread_attr_t *attr)
{
int state;
if(pthread_attr_getdetachstate(attr,&state) != 0)
{
perror("getdetachstate error");
}
else
{
if(state == PTHREAD_CREATE_DETACHED)
{
printf("state is detached\n");
}
else if(state == PTHREAD_CREATE_JOINABLE)
{
printf("stats is joinable\nl");
}
else
{
printf("unkown state\n");
}
}
}
void *th_func(void *args)
{
int i, sum = 0;
for(i = 0; i < 100; i++)
{
sum += i;
}
return (void *)sum;
}


int main(int argc, char *argv[])
{
int err = -1;
pthread_t default_th, detach_th;
//定义线程属性
pthread_attr_t attr;
//对线程属性初始化
pthread_attr_init(&attr);
//输出分离属性
out_state(&attr);

if((err = pthread_create(&default_th, &attr, th_func, (void *)0)) != 0)
{
perror("phtread create error");
return -1;
}
int res;
if((err = pthread_join(default_th, (void *)&res)))
{
perror("phtread join error");
}
else
{
printf("default return is %d\n", res);
}
printf("--------------------------------------------\n");
//设置分离属性为分离状态启动
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
out_state(&attr);
//以分离状态启动子线程
if((err = pthread_create(&detach_th, &attr, th_func, NULL)) != 0)
{
perror("pthread create failed:");
return -1;
}
if((err = pthread_join(default_th, (void *)&res)))
{
perror("phtread join error");
fprintf(stderr, "%s\n", strerror(err));
}
else
{
printf("default return is %d\n", res);
}

pthread_attr_destroy(&attr);
printf("0x%lx\n", pthread_self());
sleep(1);


return 0;
}