Advertisement
thibthibaut

Banana567777770111

Oct 6th, 2015
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.10 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. #define N_MAX 100000000LL
  6.  
  7. typedef struct {
  8.    long  thread_id; //Id du thread
  9.    double  sum; //Somme commune
  10.    int nbr_t; //Nombre de threads
  11. } thread_data;
  12.  
  13.  
  14. void* PartialSum(void* threadid);
  15.  
  16.  
  17.  
  18. int main (int argc, char* argv[]) {
  19.  
  20.     //Blindage sur les arguments en entrΓ©e
  21.     if(argc != 2 ){
  22.         printf("Invalid use of the program.\n use ./prgm <number of threads>\n");
  23.     return -1;
  24.     }
  25.  
  26.     //Conversion du nombres de threads de char* en integer
  27.     int nbrThreads = atoi( argv[1] );
  28.  
  29.     //Allocation d'un tableau de thread
  30.     pthread_t* threadArray = (pthread_t*) malloc(nbrThreads*sizeof( pthread_t ));
  31.  
  32.     double sum = 0.0;
  33.     int rc; //Initialiser la valeur de retour du pthread create
  34.     long t; //Initialiser la valeur de boucle
  35.     thread_data* myData = (thread_data*)malloc(nbrThreads * sizeof(thread_data));
  36.  
  37.     //Creations des threads
  38.     for( t = 0; t < nbrThreads; t++ ) {
  39.         //printf("creating thread %ld\n", t);
  40.  
  41.         myData[t].thread_id = t;
  42.         myData[t].sum = 0.0;
  43.         myData[t].nbr_t = nbrThreads;
  44.  
  45.         rc = pthread_create( &threadArray[t], NULL, PartialSum, (void*)&myData[t]);
  46.         if(rc) printf("Error creating thread...\n");
  47.  
  48.         (void) pthread_join(threadArray[t], NULL);
  49.  
  50.     }
  51.  
  52.     double megasum = 0.0;
  53.  
  54.     for( t = 0; t < nbrThreads; t++ ) megasum += myData[t].sum;
  55.  
  56.     free(myData);
  57.     free(threadArray);
  58.     //printf("megasum : %.12f\n",megasum);
  59.     return 0 ;
  60. }
  61.  
  62.  
  63. void* PartialSum(void* th_data) {
  64.  
  65.     thread_data* data = (thread_data*) th_data;
  66.         long myid = (long) data->thread_id;
  67.     int start = (int)(myid*N_MAX) / data->nbr_t;
  68.     int end = (int)( (myid+1) * N_MAX) / data->nbr_t;
  69.        // printf("ID: %ld, Start: %d, End: %d\n", myid, start, end);
  70.     long long  n;
  71.     start = start == 0 ? 1 : start;
  72.         for ( n = start; n < end ; n++) {
  73.                 if ( n % 2 == 0 ) {
  74.                         data->sum -= 1.0 / ( double ) n ;
  75.                 } else {
  76.                         data->sum += 1.0 / ( double ) n ;
  77.                 }
  78.         }
  79.  
  80.     //printf("My partial sum (%ld) : %.12f\n", myid, data->sum);
  81.     pthread_exit(NULL);
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement