线程属性
# 线程属性
# 线程属性
创建线程时可以指定线程的属性,需要首先创建一个属性对象,然后用这个属性对象作为参数去创建线程。
# 初始化属性对象
#include <pthread.h>
int pthread_attr_init(pthread_attr_t *attr);
1
2
2
# 销毁属性对象
#include <pthread.h>
int pthread_attr_destroy(pthread_attr_t *attr);
1
2
2
# 属性举例
# 分离线程
如果不需要新创建的线程向主函数返回参数,也不需要初始线程等待新创建的线程执行结束,此时可以指定新线程的属性为分离属性。
#include <pthread.h> int pthread_attr_setdetachstate( pthread_attr_t* attr, //属性对象 int detachstate //属性值 );
1
2
3
4
5detachstate
取值:PTHREAD_CREATE_DETACHED
:分离线程, 无需使用pthread_join()
函数合并。PTHREAD_CREATE_JOINABLE
:允许其他线 程合并此线程。
# 分离线程举例
# 示例代码
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
char message[] = "Hello World";
int thread_finished = 0;
void *thread_function(void *arg)
{
printf("thread_function is running. Argument was %s\n", (char *)arg);
sleep(4);
printf("Second thread setting finished flag, and exiting now\n");
thread_finished = 1;
pthread_exit(NULL);
}
int main()
{
int res;
pthread_t a_thread;
// void *thread_result;
pthread_attr_t thread_attr;
res = pthread_attr_init(&thread_attr);
if (res != 0)
{
perror("Attribute creation failed");
exit(EXIT_FAILURE);
}
res = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
if (res != 0)
{
perror("Setting detached attribute failed");
exit(EXIT_FAILURE);
}
res = pthread_create(&a_thread, &thread_attr, thread_function, (void *)message);
if (res != 0)
{
perror("Thread creation failed");
exit(EXIT_FAILURE);
}
(void)pthread_attr_destroy(&thread_attr);
while(!thread_finished)
{
printf("Waiting for thread to say it's finished...\n");
sleep(1);
}
printf("Other thread finished, bye!\n");
exit(EXIT_SUCCESS);
}
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
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
# 输出
Waiting for thread to say it's finished...
thread_function is running. Argument was Hello World
Waiting for thread to say it's finished...
Waiting for thread to say it's finished...
Waiting for thread to say it's finished...
Second thread setting finished flag, and exiting now
Other thread finished, bye!
1
2
3
4
5
6
7
2
3
4
5
6
7
# 分析
通过给一个新线程赋予可分离属性(PTHREAD_CREATE_DETACHED
),初始线程就不用使用pthread_join()
函数合并它,两个线程独立执行,各自独立结束。
编辑 (opens new window)
上次更新: 2023/02/18, 10:09:42
- 01
- Linux系统移植(五)--- 制作、烧录镜像并启动Linux02-05
- 03
- Linux系统移植(三)--- Linux kernel移植02-05