#include #include #include #include typedef struct { int donnee; int resultat; } typSomme; pthread_attr_t attr; void *calculSomme(void *arg) { if (((typSomme *)arg)->donnee == 1){ ((typSomme *)arg)->resultat = 1; }else{ typSomme ts; pthread_t thread; int rc; ts.donnee = ((typSomme *)arg)->donnee - 1; rc = pthread_create(&thread, &attr, 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, NULL); ((typSomme *)arg)->resultat = ((typSomme *)arg)->donnee + ts.resultat; } pthread_exit(NULL); } int main(int argc, char **argv) { int n; typSomme ts; pthread_t thread; int rc; size_t size; 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); } assert(pthread_attr_init(&attr) == 0); assert(pthread_attr_getstacksize(&attr,&size) == 0); printf("Taille de la pile (par défaut) = %d\n", size); assert(pthread_attr_setstacksize(&attr,0x4000) == 0); assert(pthread_attr_getstacksize(&attr,&size) == 0); printf("Taille de la pile (après setstacksize) = %d\n", size); ts.donnee = n; rc = pthread_create(&thread, &attr, calculSomme, &ts); if (rc){ perror("pthread_create"); exit(EXIT_FAILURE); } rc = pthread_join(thread, NULL); printf("Somme des %d premiers entiers = %d\n", n, ts.resultat); assert (pthread_attr_destroy(&attr) == 0); return EXIT_SUCCESS; }