#include #include #include #include #include typedef struct structure{ int debut; int fin; int saut; int* resultat; } structure; static inline double tstamp(void) { struct timespec tv; clock_gettime(CLOCK_REALTIME, &tv); return tv.tv_sec + tv.tv_nsec * 1.0e-9; } void *somme(void *argument) { structure data = *((structure *) argument); for (; data.debut<=data.fin; data.debut += data.saut){ *data.resultat += data.debut; } return NULL; } int main(int argc, char* argv[]) { assert(argc-1 == 2); int limite = (int) strtol(argv[1], NULL, 0); int nbThread = (int) strtol(argv[2], NULL, 0); int sommeFinal = 0; double startTime, endTime; int resultatThread[nbThread]; pthread_t threads[nbThread]; structure argument[nbThread]; for (int i = 0; i < nbThread; i++){ argument[i].debut = i; argument[i].fin = limite; argument[i].saut = nbThread; resultatThread[i] = 0; argument[i].resultat = &resultatThread[i]; } startTime = tstamp(); for (int i = 0; i < nbThread; i++){ assert( pthread_create(&threads[i], NULL, somme, &argument[i]) == 0); } for (int i = 0; i < nbThread; i++){ assert( pthread_join(threads[i], NULL) == 0); sommeFinal += *argument[i].resultat; } endTime = tstamp(); printf("somme : %d\ntemps : %lf\n", sommeFinal, endTime-startTime); return EXIT_SUCCESS; }