一叶一浮生 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
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料