UNIX环境高级编程:主线程与子线程的退出关系
发布时间:2016-10-02 04:28:01 所属栏目:Unix 来源:站长网
导读:副标题#e# 我们在一个线程中经常会创建另外的新线程,如果主线程退出,会不会影响它所创建的新线程呢?下面就来讨论一下。 1、 主线程等待新线程先结束退出,主线程后退出。正常执行。 示例代码: #include stdio.h #include stdlib.h #include pthread.h #
|
副标题[/!--empirenews.page--]
我们在一个线程中经常会创建另外的新线程,如果主线程退出,会不会影响它所创建的新线程呢?下面就来讨论一下。 1、 主线程等待新线程先结束退出,主线程后退出。正常执行。 示例代码:
#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 2344 tid 3077813952 (0xb773b6c0) new thread pid 2344 tid 3077811056 (0xb773ab70) (编辑:源码门户网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |

