【发布时间】:2009-11-06 07:40:35
【问题描述】:
以下代码使用 gcc (4.1.2 20080704) 生成错误且不一致的输出,但使用 icc (Version 11.1) 生成正确且预期的输出。但是,当我将 thread_data_array[] 定义从 main() 移动到全局时(紧接在 struct thread_data 定义之后),它在两个编译器中都可以正常工作。我不明白为什么这种变化会产生任何影响。我想递归地生成线程,所以我需要从函数中调用它,但不定义为全局的。有人可以解释一下代码有什么问题吗?
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 4
struct thread_data {
int thread_id;
int sum;
};
/* struct thread_data thread_data_array[NUM_THREADS]; */
void *p_task(void *threadarg)
{
struct thread_data *my_data;
int taskid;
int sum;
my_data = (struct thread_data *) threadarg;
taskid = my_data->thread_id;
sum = my_data->sum;
printf("Thread #%d with sum %d\n", taskid, sum);
for ( sum = 0; sum < 000000000; sum++ ) {
for ( taskid = 0; taskid < 000000000; taskid++ ) {
sum+=taskid;
}
}
return my_data;
}
int main ()
{
struct thread_data thread_data_array[NUM_THREADS]; /*this does not work*/
pthread_t threads[NUM_THREADS];
int rc;
long t;
for ( t = 0; t < NUM_THREADS; t++ ) {
thread_data_array[t].thread_id = t;
thread_data_array[t].sum = (int) t*2;
rc = pthread_create( &threads[t], NULL, p_task, (void *) &thread_data_array[t] );
}
pthread_exit(NULL);
return 0;
}
【问题讨论】:
-
gcc 版本 4.4.1 没有观察到“问题”。这可能是 GCC 中的错误吗?较早的一个是 CentOS 的最新版本,所以这让我想知道......
-
作为一个小问题,所有问题都应该有一个“这就是我所期望的”部分和一个“这就是实际发生的事情”部分:-)