Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <stdio.h>
- #include <stdlib.h>
- #define N_MAX 100000000LL
- typedef struct {
- long thread_id; //Id du thread
- double sum; //Somme commune
- int nbr_t; //Nombre de threads
- } thread_data;
- void* PartialSum(void* threadid);
- int main (int argc, char* argv[]) {
- //Blindage sur les arguments en entrΓ©e
- if(argc != 2 ){
- printf("Invalid use of the program.\n use ./prgm <number of threads>\n");
- return -1;
- }
- //Conversion du nombres de threads de char* en integer
- int nbrThreads = atoi( argv[1] );
- //Allocation d'un tableau de thread
- pthread_t* threadArray = (pthread_t*) malloc(nbrThreads*sizeof( pthread_t ));
- double sum = 0.0;
- int rc; //Initialiser la valeur de retour du pthread create
- long t; //Initialiser la valeur de boucle
- thread_data* myData = (thread_data*)malloc(nbrThreads * sizeof(thread_data));
- //Creations des threads
- for( t = 0; t < nbrThreads; t++ ) {
- //printf("creating thread %ld\n", t);
- myData[t].thread_id = t;
- myData[t].sum = 0.0;
- myData[t].nbr_t = nbrThreads;
- rc = pthread_create( &threadArray[t], NULL, PartialSum, (void*)&myData[t]);
- if(rc) printf("Error creating thread...\n");
- (void) pthread_join(threadArray[t], NULL);
- }
- double megasum = 0.0;
- for( t = 0; t < nbrThreads; t++ ) megasum += myData[t].sum;
- free(myData);
- free(threadArray);
- //printf("megasum : %.12f\n",megasum);
- return 0 ;
- }
- void* PartialSum(void* th_data) {
- thread_data* data = (thread_data*) th_data;
- long myid = (long) data->thread_id;
- int start = (int)(myid*N_MAX) / data->nbr_t;
- int end = (int)( (myid+1) * N_MAX) / data->nbr_t;
- // printf("ID: %ld, Start: %d, End: %d\n", myid, start, end);
- long long n;
- start = start == 0 ? 1 : start;
- for ( n = start; n < end ; n++) {
- if ( n % 2 == 0 ) {
- data->sum -= 1.0 / ( double ) n ;
- } else {
- data->sum += 1.0 / ( double ) n ;
- }
- }
- //printf("My partial sum (%ld) : %.12f\n", myid, data->sum);
- pthread_exit(NULL);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement