Hello, The following code produces wrong and inconsistent output with gcc (4.1.2 20080704) but correct and expected output with icc (Version 11.1) . But when I moved the thread_data_array[] definition from main() to global (immediately after the struct thread_data definition) it works fine with both compilers. I do not see why this change should make any difference. I would like to generate threads recursively so I need to call it from a function but not define as global. Could someone explain what is wrong the code please?
#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;
}