红联Linux门户
Linux帮助

线程创建的参数传递

发布时间:2010-11-12 10:38:16来源:红联作者:wucongdonglai
对于进城创建的参数传递还是有些疑问,不大明白,例子程序如下
#define _REENTRANT
#include
#include
#include
#include
#include

#define NUM_THREADS 6
void *thread_function(void *arg);
int main() {

int res;
pthread_t a_thread[NUM_THREADS];
void *thread_result;
int lots_of_threads;
//挨个建立线程
for(lots_of_threads = 0; lots_of_threads < NUM_THREADS; lots_of_threads++) {
//这里的参数lots_of_threads是如何传递给线程的?
res = pthread_create(&(a_thread[lots_of_threads]));
if (res != 0) {
perror("Thread creation failed");
exit(EXIT_FAILURE);
}
}

printf("Waiting for threads to finish...\n");
//挨个等待线程结束比较有疑问的是
for(lots_of_threads = NUM_THREADS - 1; lots_of_threads >= 0; lots_of_threads--) {
res = pthread_join(a_thread[lots_of_threads], &thread_result);
if (res !== 0) perror("pthread_join failed");
}

printf("All done\n");

exit(EXIT_SUCCESS);
}

void *thread_function(void *arg) {
[color=#00ff00]//为何参数lots_of_threads变成了arg了?
int my_number = (int)arg;
printf("Bye from %d\n", my_number);
pthread_exit(NULL);
}[/color]

这程序的结果是有错误的,因为如果主程序运行的足够快的话,可能会改变某些线程的参数的,所以程序结果是不确定的!
但是想这样调用pthread_create(&(a_thread[lots_of_threads]))是怎么传递参数的
文章评论

共有 0 条评论