minh_tran_782

Calculate Pi Multi-thread

Feb 26th, 2022 (edited)
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.13 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <time.h>
  4. #include <math.h>
  5. #include <pthread.h>
  6. const int NUM_THREADS = 4;
  7.  clock_t start, end;
  8.  
  9. static int count = 0;
  10. void* circle_cnt(void* loopTimes)
  11. {   int times = 0;
  12.     int loop = (int)loopTimes;
  13.  
  14.      for(int i=0;i<loop;i++)
  15.     {
  16.         double x=(double)rand()/((double)RAND_MAX);
  17.         double y=(double)rand()/((double)RAND_MAX);
  18.         double distance= 1.0*x*x+1.0*y*y;
  19.         if(distance<=1) times++;
  20.     }
  21.     count = count + times;
  22.     pthread_exit(NULL);
  23. }
  24. int main(int argc, char*argv[])
  25. {  
  26.         pthread_t tid[NUM_THREADS];
  27.     int n=atoi(argv[1]);
  28.     int div = n/NUM_THREADS;
  29.     double pi = 1.0;
  30.     srand(time(NULL));
  31.     start = clock();
  32.     int i = 0;
  33.     for (i = 0; i < NUM_THREADS; ++i)
  34.     {
  35.         //pthread_attr_t attr;
  36.         //pthread_attr_init(&attr);
  37.         pthread_create(&tid[i], NULL, circle_cnt, (void*) div);
  38.     }
  39.     for (i = 0; i < NUM_THREADS; ++i)
  40.     {
  41.         pthread_join(tid[i], NULL);
  42.     }
  43.     pi=4.0*count/n;
  44.         end = clock();
  45.         double exe_time = ((double)(end - start)) / ( (double)(CLOCKS_PER_SEC) );
  46.     printf("Pi: %lf\n",pi);
  47.         printf("Time: %g seconds", exe_time);
  48.      
  49.     return 0;
  50. }
  51.  
Add Comment
Please, Sign In to add comment