函数调用先后顺序的问题

#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,本人小白,求大侠指点,感谢?

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

线程和主进程 是时间片占用CPU的, 也就是说这两个线程之间不是同步的,不分先后顺序执行

多线程序就没有顺序的概念了,除非加代码让它们有序运行,这就又回到单线程了