w810443616 2015-09-28 09:58 采纳率: 80%
浏览 2195
已采纳

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: %d\n",*runing);
while(*runing){
printf("The child thread is runing !\n");
usleep(1);
}
printf("Exit child thread\n");
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 %d\n",*ret_join);
return 0;
}
在子线程中,while循环是一个死循环,那个子线程如何退出终止的?各位大神,求解答!谢了各位!总是在线程这里玩儿不明白...

  • 写回答

2条回答 默认 最新

  • .千山. 2015-09-28 12:40
    关注

    哥们,子线程哪是一个死循环呢。。。 子线程循环条件就是run>0, 程序开始运行后,因为usleep()作用在主线程和线程之间切换执行,主线程执行到run=0后,子线程的循环条件也不存在就结束了呗

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵