Advertisement
minh_tran_782

[Speed-up Multi-thread version] pi_multi-thread.c

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