#include #include #include #include typedef struct { int donnee; } typSomme; void *calculSomme(void *arg) { int *pResultat; int *pResThreadAppelee = NULL; assert( (pResultat = malloc(sizeof(int))) != NULL ); if (((typSomme *)arg)->donnee == 1){ *pResultat = 1; }else{ typSomme ts; pthread_t thread; int rc; ts.donnee = ((typSomme *)arg)->donnee - 1; rc = pthread_create(&thread, NULL, calculSomme, &ts); if (rc){ perror("pthread_create"); fprintf(stderr, "((typSomme *)arg)->donnee valait %d\n", ((typSomme *)arg)->donnee); exit(EXIT_FAILURE); } rc = pthread_join(thread, (void**)&pResThreadAppelee); *pResultat = ((typSomme *)arg)->donnee + *pResThreadAppelee; free(pResThreadAppelee); pResThreadAppelee = NULL; } pthread_exit(pResultat); } int main(int argc, char **argv) { int n; typSomme ts; pthread_t thread; int rc; int *pResThreadAppelee; if (argc < 2) { fprintf(stderr, "Usage: %s entierStrictementPositif\n", argv[0]); exit(EXIT_FAILURE); } n = atoi(argv[1]); if (n <= 0){ fprintf(stderr, "Usage: %s entierStrictementPositif\n", argv[0]); exit(EXIT_FAILURE); } ts.donnee = n; rc = pthread_create(&thread, NULL, calculSomme, &ts); if (rc){ perror("pthread_create"); exit(EXIT_FAILURE); } rc = pthread_join(thread, (void**)&pResThreadAppelee); printf("Somme des %d premiers entiers = %d\n", n, *pResThreadAppelee); free(pResThreadAppelee); pResThreadAppelee = NULL; return EXIT_SUCCESS; }