首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

LINUX关于pthread_create 和pthread_join解决思路

2012-02-10 
LINUX关于pthread_create 和pthread_join各位大牛,本人学习中遇到一些疑问源代码:[codeC/C++][/code]#inc

LINUX关于pthread_create 和pthread_join
各位大牛,
本人学习中遇到一些疑问

源代码:
[code=C/C++][/code]#include <stdio.h>
#include <pthread.h>
void thread1(void)
{
int i;
for(i = 0; i < 6; i++)
{
printf("this is thread1\n");
if( i == 2)
{
pthread_exit(0);
}
sleep(2);
}
}
void thread2(void)
{
int i;
for(i = 0; i < 3; i++)
{
printf("this is thread2\n");
}
pthread_exit(0);
}
int main()
{
pthread_t id1,id2;
int i,ret;
printf("step 1\n");
ret = pthread_create(&id1, NULL, (void *)thread1,NULL);
if(ret != 0)
{
printf("create failed\n");
exit(1);
}
else
{
printf("create 1sucess\n");
}
printf("step 2\n");
ret = pthread_create(&id2, NULL, (void *)thread2,NULL);
if(ret != 0)
{
printf("create failed\n");
exit(1);
}
else
{
printf("create 2sucess\n");
}
printf("step 3\n");
pthread_join(id1, NULL);
printf("step 4\n");
pthread_join(id2, NULL);
printf("step 5\n");
exit(0);
}

运行结果:

[lb@sky study]$ ./pthread
step 1
create 1sucess
step 2
create 2sucess
step 3
this is thread1
this is thread2
this is thread2
this is thread2
this is thread1
this is thread1
step 4
step 5

疑问:
1:线程是在create了立即执行还是在pthread_join了执行?
2:为什么输出是
this is thread1
this is thread2
this is thread2
this is thread2
this is thread1
this is thread1
这样的顺序?
3:帮我分析输出信息为什么是step 3过后输出this is thread1?


[解决办法]
线程的执行顺序是由调度算法决定的,输出顺序不一样也是可能的,各个线程之间也是互相竞争cpe时间的
线程在这里的create之后就会执行,pthread_join的作用是等待线程执行完毕

热点排行