描述:下面是屏蔽pthread_join(id,NULL);之后的执行效果截图
图片:
描述:下面是没有屏蔽pthread_join(id,NULL);的执行效果截图
图片:
问题具体描述及相关代码:看囯嵌的视频中,进程中用pthread_create建立一个线程以后,线程是就绪态,并没立即执行,而是继续执行进程中的代码,除非加pthread_join,才先执行线程,线程退出后才继续执行进程。
但我现在遇到的问题是:建立好线程后,它就直接执行线程中的内容了,也就是加与不加pthread_join都是优先执行线程,请问如何解决呢》?
如下面代码:
代码:
#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
分析:
按老师的说法,屏蔽掉pthread_join(id,NULL);
的话,应该执行不到线程,直接返回退出了,但执行效果不是。
主程序进程执行到
sleep(1);printf("this is the main thread\n");
的sleep(1)这句时,并没执行printf("this is the main thread\n");
而是去执行线程了,执行完线程中的输出,在线程sleep时才又回到进程中,并return,结束,所以有上面的结果,不像老师说的那样,主进程创建线程时先继续运行进程。求解答?谢谢!!
[ 此帖被hyb8555在2011-05-17 14:30重新编辑 ]