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说的那样,主进程创建线程时先运行进程。