Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <time.h>
- #include <math.h>
- #include <pthread.h>
- const int NUM_THREADS = 4;
- clock_t start, end;
- struct countEachThread
- {
- int limit;
- int count;
- };
- _Thread_local unsigned int seed = 0;
- void* circle_cnt(void* argp)
- { int count = 0;
- struct countEachThread* ptr = (struct countEachThread*)argp;
- for(int i=0;i < ptr->limit;i++)
- {
- int n = rand_r(&seed);
- double x=(double)n/((double)RAND_MAX);
- n = rand_r(&seed);
- double y=(double)n/((double)RAND_MAX);
- double distance= 1.0*x*x+1.0*y*y;
- if(distance<=1) count++;
- }
- ptr->count = count;
- pthread_exit(NULL);
- }
- int main(int argc, char*argv[])
- {
- pthread_t tid[NUM_THREADS];
- struct countEachThread calc[NUM_THREADS];
- int n = atoi(argv[1]); // input
- srand(time(NULL));
- start = clock(); // init start time.
- int i = 0; // init loop variable
- for (i = 0; i < NUM_THREADS; ++i) // create NUM_THREADS threads to calculate
- {
- pthread_attr_t attr;
- pthread_attr_init(&attr);
- calc[i].limit = n / NUM_THREADS;
- pthread_create(&tid[i], &attr, circle_cnt,&calc[i]);
- }
- int countTotal = 0;
- for (i = 0; i < NUM_THREADS; ++i) // join threads together.
- {
- pthread_join(tid[i], NULL);
- countTotal = countTotal + calc[i].count;
- }
- double pi = 4.0 * countTotal / n;
- end = clock();
- double exe_time = ((double)(end - start)) / ( (double)(CLOCKS_PER_SEC) );
- printf("Pi: %lf\n",pi);
- printf("Time: %g seconds", exe_time);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement