Home > other >  Pthread unlocked, multithreading is slower than the single thread instead
Pthread unlocked, multithreading is slower than the single thread instead

Time:09-20

Today when the course experiment, using the monte carlo algorithm for pai, requirements by using pthread to improve performance, the results after using the multithreading, longer running time than single thread, please leaders to help!
# include & lt; Stdio. H>
# include & lt; Stdlib. H>
# include & lt; Math. H>
# include & lt; Time. H>
# include & lt; Pthread. H>

Long long sum=100000000;
Long long num_circle=0;
Int thread_count;


Void * compute rank (void *);

Int main (int arg c, char * argv []) {
Long thread;
Pthread_t * thread_handlers;

//read the number of threads
Thread_count=strtol (argv [1], NULL, 10);
//printf (" % d \ n ", thread_count);

//the thread memory space
Thread_handlers=malloc (thread_count * sizeof (pthread_t));

Clock_t start and end;
//start the time
Start=clock ();

//initialize the random number seed
Srand (time (0));

//create thread_count thread
For (thread=0; Thread & lt; Thread_count; The thread + +) {
Pthread_create (& amp; Thread_handlers (thread), NULL, compute, (void *) thread);
}

//merge thread_count thread
For (thread=0; Thread & lt; Thread_count; The thread + +) {
Pthread_join (thread_handlers [thread], NULL);
}
Free (thread_handlers);
//the end time
End=clock ();

//computing available
Double duaration=(double) (end - start)/CLOCKS_PER_SEC;
Double pai=num_circle * 1.0/sum * 4;
Printf (" finished in seconds f \ % n % f ", duaration, pai);
}

Void * compute rank (void *) {
Long my_rank=(long) rank;
Int my_start=my_rank * (sum/thread_count);
Int my_end=(my_rank + 1) * (sum/thread_count) - 1;
For (int I=my_start; I & lt;=my_end; I + +) {
Double x=2.0 * rand ()/RAND_MAX - 1;
Double y=2.0 * rand ()/RAND_MAX - 1;
Double distance_squared=SQRT (x * * y x + y);
If (distance_squared & lt; {
=1.0)Num_circle + +;
}
}

//printf (" % f \ n ", distanc_squared);
Return rank;
}
  • Related