您的位置:首页 > 运维架构 > Linux

linux小实验(1)---线程

2013-09-13 11:25 357 查看
(1)、线程会随创建它的进程死掉而死掉

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void *thread(void *);

int main()
{
pthread_t t_a;
pthread_t t_b;

pthread_create(&t_a,NULL,thread,(void *)1);
pthread_create(&t_b,NULL,thread,(void *)2);
printf("main process is teminated!\n");
exit(0);
}

void *thread(void *junk)
{
int i=1;

for(i=1;i<=4;i++)
{
printf("thread %d ...\n",(int)junk);
sleep(1);
}
pthread_exit(0);
}


(2)、线程不会随创建它的线程死掉而死掉

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void *thread_parent(void *);
void *thread_child(void *);

int main()
{
pthread_t t;
void* ret;

pthread_create(&t,NULL,thread_parent,(void *)0);

pthread_join(t,&ret);
printf("parent thread process is terminated.\n");

sleep(10);

printf("main process is teminated!\n");
exit(0);

}

void *thread_parent(void *para)
{
pthread_t t1,t2;

pthread_create(&t1,NULL,thread_child,(void *)1);
pthread_create(&t2,NULL,thread_child,(void *)2);
pthread_exit(0);
}

void *thread_child(void *para)
{
int i=1;
for(i=1;i<=4;i++)
{
printf("child thread %d...\n",(int)para);
sleep(1);
}
printf("child thread %d t is terminated!\n",(int)para);
pthread_exit(0);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: