UNIX环境高级编程:主线程与子线程的退出关系
发布时间:2016-10-02 04:28:01 所属栏目:Unix 来源:站长网
导读:副标题#e# 我们在一个线程中经常会创建另外的新线程,如果主线程退出,会不会影响它所创建的新线程呢?下面就来讨论一下。 1、 主线程等待新线程先结束退出,主线程后退出。正常执行。 示例代码: #include stdio.h #include stdlib.h #include pthread.h #
|
示例代码:
#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 *thrfun2(void *arg){
sleep(1);//使得创建它的主线程先退出
printids("new thread of the new thread");
return ((void *)0);
}
void *thrfun(void *arg){
sleep(1);//使得主线程先退出
printids("new thread");
int err;
err = pthread_create(&ntid,NULL,thrfun2,NULL);
if(err != 0)
perror("pthread_create");
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);
}
运行结果: huangcheng@ubuntu:~$ ./a.out main thread pid 2413 tid 3077912256 (0xb77536c0) new thread pid 2413 tid 3077909360 (0xb7752b70) new thread of the new thread pid 2413 tid 3069516656 (0xb6f51b70) 作者信息:csdn博客 ctthuangcheng (编辑:源码门户网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |

