为了账号安全,请及时绑定邮箱和手机立即绑定

为什么运行结果为下面的情况呢?求解释

为什么运行结果为下面的情况呢?求解释

忽然笑 2023-03-03 14:10:38
代码如下:#include<pthread.h>#include<stdio.h>#define MAX_THREADS 5void *myThread(void *arg){printf("Thread %d started\n", (unsigned int)arg);pthread_exit(arg);}int main(){int ret, i, status;pthread_t threadids[MAX_THREADS];for(i=0; i<MAX_THREADS; i++){ret=pthread_create(&threadids[i], NULL, myThread, (void*)i);if(ret!=0)printf("error creating thread %d\n", i);}for(i=0; i<MAX_THREADS; i++){ret=pthread_join(threadids[i], (void** )&status);if(ret!=0)printf("error joining thread %d\n", i);elseprintf("status=%d\n",status);}return 0;}为什么运行结果为:Thread 3 startedThread 4 startedThread 2 startedThread 1 startedThread 0 startedstatus=0status=1status=2status=3status=4谢谢!
查看完整描述

2 回答

?
皈依舞

TA贡献1851条经验 获得超3个赞

Linux系统pthread_join用于挂起当前线程(调用pthread_join的线程),直到thread指定的线程终止运行为止,当前线程才继续执行。

案例代码:


/*********************************************    Name:pthread_join.c**    用于Linux下多线程学习**    案例解释线程的暂停和结束**    Author:admin**    Date:2015/8/11       **    Copyright (c) 2015,All Rights Reserved!**********************************************#include <pthread.h>#include <unistd.h>#include <stdio.h>void *thread(void *str){    int i;    //不调用pthread_join线程函数    for (i = 0; i < 10; ++i)    {        sleep(2);        printf"This in the thread : %d\n" , i );    }    return NULL;} int main(){    pthread_t pth;    int i;    int ret = pthread_create(&pth, NULL, thread, (void *)(i));    //调用pthread_join线程函数    pthread_join(pth, NULL);    for (i = 0; i < 10; ++i)    {        sleep(1);        printf"This in the main : %d\n" , i );    }         return 0;}

通过Linux下shell命令执行上面的案例代码:


[root@localhost src]# gcc pthread_join.c -lpthread[root@localhost src]# ./a.outThis in the main : 0This in the thread : 0This in the main : 1This in the main : 2This in the thread : 1This in the main : 3This in the main : 4This in the thread : 2This in the main : 5This in the main : 6This in the thread : 3This in the main : 7This in the main : 8This in the thread : 4This in the main : 9

子线程还没有执行完毕,main函数已经退出,那么子线程也就退出了,“pthread_join(pth, NULL);”函数起作用。


[root@localhost src]# gcc pthread_join.c -lpthread[root@localhost src]# ./a.outThis in the thread : 0This in the thread : 1This in the thread : 2This in the thread : 3This in the thread : 4This in the thread : 5This in the thread : 6This in the thread : 7This in the thread : 8This in the thread : 9This in the main : 0This in the main : 1This in the main : 2This in the main : 3This in the main : 4This in the main : 5This in the main : 6This in the main : 7This in the main : 8This in the main : 9

这说明pthread_join函数的调用者在等待子线程退出后才继续执行。

 


查看完整回答
反对 回复 2023-03-06
?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

这是随机情况,由系统调度决定,不是唯一的结果,你可以尝试这样改:ret=pthread_create(&threadids[i], NULL, myThread, (void*)i);
sleep(1);
这样就是按顺序创建线程


查看完整回答
反对 回复 2023-03-06
  • 2 回答
  • 0 关注
  • 181 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号