一叶一浮生 2016-03-08 17:35 采纳率: 0%
浏览 1395

函数调用先后顺序的问题

#include

#include

#include

#define THREAD_NUMBER 3//线程个数

#define REPEAT_NUMBER 5

#define DELAY_TIME_LEVELS 10.0

void *thrd_func(void *arg)//线程函数

{

int thrd_num = (int)arg ;

int delay_time = 0 ;

int count = 0 ;

printf("thread %d is starting\n", thrd_num) ;

for (count = 0; count < REPEAT_NUMBER; count++)//每个线程完成五次任务

{

delay_time = (int)(rand() * DELAY_TIME_LEVELS/(RAND_MAX)) + 1;//产生随机时间

sleep(delay_time) ;

printf("\tThread %d:job %d delay = %d\n",

thrd_num, count, delay_time) ;

}

printf("thread %d finished\n", thrd_num) ;

pthread_exit(NULL) ;

}

int main()

{

pthread_t thread[THREAD_NUMBER] ;

int no = 0, res ;

void *thrd_ret ;

srand(time(NULL)) ;//产生随机种子

for(no = 0; no < THREAD_NUMBER; no++)

{

res = pthread_create(&thread[no], NULL, thrd_func, (void *)no) ;//创建线程

if (res != 0)

{

printf("create thread %d failed\n", no) ;

exit(res) ;

}

}

printf("create threads success\n waiting for threads to finish...\n") ;

for (no = 0; no < THREAD_NUMBER; no++)

{

res = pthread_join(thread[no], &thrd_ret) ;//等待线程结束

if (!res)

{

printf("thread %d joined\n", no) ;

}

else

{

printf("thread %d joined failed", no) ;

}

}

exit(0) ;

}

为什么首先输出的是这段create threads success waiting for threads to finish...,不是应该先调用了线程函数么,为什么首先输出的不是thread %d is starting,本人小白,求大侠指点,感谢?

  • 写回答

3条回答

  • threenewbee 2016-03-09 00:56
    关注

    调用线程函数不等于先执行它,线程调用是异步的,执行顺序是随机的。

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!