Advertisement
minh_tran_782

pi_multi-thread.c [Avoid race condition]

Feb 27th, 2022
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.57 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.  struct countEachThread
  9.  {
  10.  int limit;
  11.  int count;  
  12.  };
  13.  _Thread_local unsigned int seed = 0;
  14.  
  15. void* circle_cnt(void* argp)
  16. {   int count = 0;
  17.     struct countEachThread* ptr = (struct countEachThread*)argp;  
  18.      for(int i=0;i < ptr->limit;i++)
  19.     {
  20.      
  21.    
  22.         int n = rand_r(&seed);
  23.         double x=(double)n/((double)RAND_MAX);
  24.        
  25.         n = rand_r(&seed);
  26.         double y=(double)n/((double)RAND_MAX);
  27.        
  28.         double distance= 1.0*x*x+1.0*y*y;
  29.        
  30.         if(distance<=1) count++;
  31.        
  32.      
  33.     }
  34.     ptr->count = count;
  35.     pthread_exit(NULL);
  36. }
  37. int main(int argc, char*argv[])
  38. {  
  39.         pthread_t tid[NUM_THREADS];
  40.    
  41.     struct countEachThread calc[NUM_THREADS];
  42.    
  43.     int n = atoi(argv[1]); // input
  44.    
  45.     srand(time(NULL));
  46.    
  47.     start = clock(); // init start time.
  48.    
  49.     int i = 0;   // init loop variable
  50.    
  51.     for (i = 0; i < NUM_THREADS; ++i) // create NUM_THREADS threads to calculate
  52.     {
  53.         pthread_attr_t attr;
  54.         pthread_attr_init(&attr);
  55.         calc[i].limit = n / NUM_THREADS;  
  56.         pthread_create(&tid[i], &attr, circle_cnt,&calc[i]);
  57.     }
  58.     int countTotal = 0;
  59.  
  60.     for (i = 0; i < NUM_THREADS; ++i) // join threads together.
  61.     {
  62.         pthread_join(tid[i], NULL);
  63.         countTotal = countTotal + calc[i].count;
  64.     }
  65.  
  66.     double pi = 4.0 * countTotal / n;
  67.  
  68.         end = clock();
  69.  
  70.         double exe_time = ((double)(end - start)) / ( (double)(CLOCKS_PER_SEC) );
  71.  
  72.     printf("Pi: %lf\n",pi);
  73.  
  74.         printf("Time: %g seconds", exe_time);
  75.      
  76.     return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement