UNIX环境高级编程:主线程与子线程的退出关系
发布时间:2016-09-27 12:21:23 所属栏目:Unix 来源:站长网
导读:副标题#e# 我们在一个线程中经常会创建另外的新线程,如果主线程退出,会不会影响它所创建的新线程呢?下面就来讨论一下。 1、 主线程等待新线程先结束退出,主线程后退出。正常执行。 示例代码: #include stdio.h #include stdlib.h #include pthread.h #
2、 进程先退出,新线程也会立即退出,系统清除所有资源。 示例代码: #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <sys/types.h> pthread_t ntid;//线程ID void printids(const char *s) { pid_t pid; pthread_t tid; pid = getpid(); tid = pthread_self(); printf("%s pid %u tid %u (0x%x)n",s,(unsigned int)pid, (unsigned int)tid,(unsigned int)tid); } void *thrfun(void *arg){ sleep(1);//使得主线程先退出 printids("new thread"); return ((void *)0); } int main(){ int err; err = pthread_create(&ntid,NULL,thrfun,NULL); if(err != 0) perror("pthread_create"); printids("main thread"); //sleep(1);//等待新线程先结束 exit(0); } 运行结果: huangcheng@ubuntu:~$ ./a.out main thread pid 2366 tid 3077641920 (0xb77116c0) 可以发现主线程退出后所创建的新线程也停止运行了。 3、如果主线程调用了pthread_exit,那么它退出了,子线程也不会退出。 示例代码: #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <sys/types.h> pthread_t ntid;//线程ID void printids(const char *s) { pid_t pid; pthread_t tid; pid = getpid(); tid = pthread_self(); printf("%s pid %u tid %u (0x%x)n",s,(unsigned int)pid, (unsigned int)tid,(unsigned int)tid); } void *thrfun(void *arg){ sleep(1);//使得主线程先退出 printids("new thread"); return ((void *)0); } int main(){ int err; err = pthread_create(&ntid,NULL,thrfun,NULL); if(err != 0) perror("pthread_create"); printids("main thread"); //sleep(1);//等待新线程先结束 pthread_exit(NULL); // exit(0); } 查看本栏目更多精彩内容:http://www.bianceng.cn/OS/unix/ (编辑:应用网_丽江站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |