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

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

    评论

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元