主题 : 线程执行顺序 复制链接 | 浏览器收藏 | 打印
级别: 新手上路
UID: 18505
精华: 0
发帖: 48
金钱: 250 两
威望: 50 点
综合积分: 96 分
注册时间: 2010-04-10
最后登录: 2011-05-05
楼主  发表于: 2010-06-11 21:41

 线程执行顺序

#include<stdio.h>
#include<pthread.h>
void thread(void)
{
int i;
for(i=0;i<10;i++){
sleep(1);
printf("this is %d pthread\n,i");
}
}
int main(void)
{
pthread_t id;
int i,ret;
ret = pthread_creat(&id,NULL,(void*)thread,NULL);
if(ret!=0){
printf("creat error");
exit(1);
}
for(i=0;i<10;i++)
{
sleep(1);
printf("this is the main thread\n");
pthread_join(id,NULL);
return 0;
}
}
执行结果为
this is the main thread
this is 0 pthread
this is the main thread
this is 1 pthread
this is the main thread
this is 2 pthread
this is the main thread
this is 3 pthread
this is the main thread
this is 4 pthread
this is the main thread
this is 5 pthread
this is the main thread
this is 6 pthread
this is the main thread
this is 7 pthread
this is the main thread
this is 8 pthread
this is the main thread
this is 9 pthread
可见主进程创建线程时先运行进程
学习交流
爱我所爱,做我所做。
级别: 新手上路
UID: 40950
精华: 0
发帖: 22
金钱: 110 两
威望: 22 点
综合积分: 44 分
注册时间: 2011-03-24
最后登录: 2013-03-05
1楼  发表于: 2011-05-17 11:11
lz的解释和我运行的有出入:

代码:
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>
void thread(void)
{
int i;
for(i=0;i<10;i++){
sleep(1);
printf("this is %d pthread\n",i);
}
}
int main(void)
{
pthread_t id;
int i,ret;
ret = pthread_create(&id,NULL,(void*)thread,NULL);
if(ret!=0){
printf("creat error");
exit(1);
}
for(i=0;i<10;i++)
{
sleep(1);
printf("this is the main thread\n");
//pthread_join(id,NULL);
return 0;
}
}

执行效果
this is 0 pthread
this is the main thread

分析:
按lz说法,屏蔽掉pthread_join(id,NULL);
的话,应该执行不到线程,直接返回退出了,但执行效果不是。
主程序进程执行到
sleep(1);
printf("this is the main thread\n");
sleep这句时,并没执行printf("this is the main thread\n");
而是去执行线程了,执行完线程中的输出,在线程sleep时才又回到进程中,并return,结束,所以有上面的结果,不想lz说的那样,主进程创建线程时先运行进程。
做我想做之事,爱我所爱之人!
爱我所爱,做我所做。
级别: 新手上路
UID: 40950
精华: 0
发帖: 22
金钱: 110 两
威望: 22 点
综合积分: 44 分
注册时间: 2011-03-24
最后登录: 2013-03-05
2楼  发表于: 2011-05-17 11:50
而加上pthread_join(id,NULL);
这句的时候,执行效果是
this is the main thread
this is 0 pthread
this is 1 pthread
this is 2 pthread
this is 3 pthread
this is 4 pthread
this is 5 pthread
this is 6 pthread
this is 7 pthread
this is 8 pthread
this is 9 pthread
分析:先执行了一次主进程中的printf("this is the main thread\n");
之后,遇到pthread_join(id,NULL);
这句,进而转去执行线程中内容,输出后,虽然遇到sleep(1),但此时的sleep也只是为其他进程让cpu,主进程由于执行了pthread_join(id,NULL);
会一直等它要等的这个线程退出以后才继续往下执行。直到线程中的i=10,线程退出,结束pthread_join(id,NULL);
,继续往下执行主进程中内容,而此时主进程只有return 0了,所以返回退出,才出现如上所述效果。
为什么会和lz同一个程序出校不同的执行效果呢?
求一个权威的解答!!!!
做我想做之事,爱我所爱之人!