日期:2014-05-16  浏览次数:20878 次

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的作用是等待线程执行完毕