一叶一浮生 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 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题