基础知识
默认情况下,线程被创建成可结合的。为了避免存储器泄漏,每个可结合线程都应该被显示回收,即调用pthread_join,或通过调用pthread_detach函数被分离。
1)如果一个可结合线程运行结束但没有被join,则它的状态类似与僵尸进程。
2)若调用pthread_join后,该线程还没有结束运行,调用者会被阻塞。为了避免此现象,可在子线程中加入代码
pthread_detach(pthread_self())
或者父线程调用
pthread_detach(thread_id)(非阻塞,可立即返回)
这将该子线程的状态设置为分离的(detached),如此一来,该线程运行结束后会自动释放所有资源。
2.代码实现
//detach.c
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<pthread.h>
4
5 void* thread_run(void* val)
6 {
7 pthread_detach(pthread_self());
8 printf("%s\n",(char*)val);
9 return NULL;
10 }
11 int main()
12 {
13 pthread_t tid;
14 int tret=pthread_create(&tid,NULL,thread_run,"thread_run run...");
15 if(tret!=0)
16 {
17 printf("create pthread error!,info is:%s\n",strerror(tret));
18 return tret;
19 }
20 int ret;
21 sleep(1);
22 if(0==pthread_join(tid,NULL))
23 {
24 printf("thread wait success!\n");
25 ret=0;
26 }
27 else
28 {
29 printf("pthread wait failed!\n");
30 ret=1;
31 }
32 return ret;
33 }
//makefile
1 detach:detach.c
2 gcc -o $@ $^ -lpthread
3 .PHONY:clean
4 clean:
5 rm -f detach输出结果:
本文出自 “sunshine225” 博客,请务必保留此出处http://10707460.blog.51cto.com/10697460/1765833
原文地址:http://10707460.blog.51cto.com/10697460/1765833