问题描述
- linux C 线程终止问题,着急,求各位大神帮忙
-
include
#include
#include
static int run = 1;
static int retvalue;
void *start_routine(void *arg){
int *runing = arg;
printf("The child thread has been inited,the arg is: %dn",*runing);
while(*runing){
printf("The child thread is runing !n");
usleep(1);
}
printf("Exit child threadn");
retvalue = 8;
pthread_exit((void *)&retvalue);
}int main(void){
pthread_t pt;
int ret = -1;
int times = 3;
int i = 0;
int ret_join = NULL;
ret = pthread_create(&pt,NULL,(void)start_routine,&run);
if(ret !=0){
printf("Create thread fail!n");
return 1;
}
usleep(1);
for(;i < times;i++){
printf("Print the main thread!n");
usleep(1);
}
run = 0;
pthread_join(pt,(void*)&ret_join);
printf("The return of thread is %dn",*ret_join);
return 0;
}
在子线程中,while循环是一个死循环,那个子线程如何退出终止的?各位大神,求解答!谢了各位!总是在线程这里玩儿不明白...
解决方案
哥们,子线程哪是一个死循环呢。。。 子线程循环条件就是run>0, 程序开始运行后,因为usleep()作用在主线程和线程之间切换执行,主线程执行到run=0后,子线程的循环条件也不存在就结束了呗
解决方案二:
啊啊啊,哥哥!谢谢了!我真没注意!我是看着书上例子,他没有注释,usleep函数的用处。。。所以我就用我电脑试了试 结果真行,让后就郁闷了,谢了哥!我没分,感谢感谢!
时间: 2024-09-13 21:47:56