Le code suivant génère une sortie incorrecte et incohérente avec gcc (4.1.2 20080704) mais une sortie correcte et attendue avec icc (version 11.1). Mais quand j'ai déplacé la définition de thread_data_array [] de main() à global (immédiatement après la définition de struct thread_data) cela fonctionne bien avec les deux compilateurs. Je ne vois pas pourquoi ce changement devrait faire la différence. Je voudrais générer des threads de façon récursive, donc je dois l'appeler à partir d'une fonction mais pas définir comme global. Quelqu'un pourrait-il expliquer ce qui ne va pas le code s'il vous plaît?pthreads: incohérence entre gcc et icc sous Linux
#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;
}
Le 'problème' n'est pas observé avec la version 4.4.1 de gcc. Cela pourrait-il être un bug dans GCC? Le plus ancien était le dernier de CentOS, donc je me demande ... – user203405
Juste comme un point mineur, toutes les questions devraient avoir une section «c'est ce que j'attends» et une section «c'est ce qui se passe réellement» :-) – paxdiablo
Je l'ai, sire. : D – user203405