首页 > 技术文章 > 线程分离pthread_detach()中的return()和pthread_exit()

fallenmoon 2017-04-26 16:32 原文

 

 1 #include <stdio.h>
 2 #include <pthread.h>
 3 
 4 pthread_t tid[2];
 5 void *func_2(void *arg);
 6 void *func_1(void *arg)
 7 {       //为函数func_2创建线程
 8         printf("Starting func_1\n");
 9         pthread_create(&tid[1], NULL, func_2, NULL);
10         //tid[0]将自己挂起,等待线程tid[1]的结束
11         pthread_join(tid[1], NULL);
12 }
13 
14 void *func_2(void *arg)
15 {
16         printf("Starting func_2\n");
17         sleep(1);
18         pthread_exit(NULL);
19 }
20 
21 int main()
22 {       //为函数func_1创建线程并将其分离
23         pthread_create(&tid[0], NULL, func_1, NULL);
24 //      pthread_detach(tid[0], NULL);   //分离
25         pthread_detach(tid[0]); //分离
26         //主线程不退出,但这两个现成的资源都可以释放掉
27 //      return 0;
28         pthread_exit(NULL);
29 }

在main()函数中,如果采用return 0,则没有任何输出就退出了;而如果采用的是pthread_exit(NULL),则打印出消息

 

推荐阅读