Advertisement
David_Anicic

monte-carlo-os2.c

Oct 22nd, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.51 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>
  4. #include<math.h>
  5. #include <pthread.h>
  6.  
  7. #define NUMTHRDS 4
  8. #define N 100000000
  9. pthread_mutex_t mutex;
  10.  
  11. double globalUnutra;
  12.  
  13. void *BusyWork(void*arg)
  14. {
  15.     long tid = (long)arg;
  16.  
  17.     int i;
  18.     double x, y;
  19.     double unutra = 0.0;
  20.     for (i=tid*N/NUMTHRDS; i<(tid*N/NUMTHRDS)+N/NUMTHRDS; i++)
  21.     {
  22.         x = rand() * 1.0 / RAND_MAX;
  23.         y = rand() * 1.0 / RAND_MAX;
  24.         if((x*x + y*y) <= 1.0)
  25.          unutra++;
  26.     }
  27.  
  28.     pthread_mutex_lock(&mutex);
  29.     globalUnutra += unutra;
  30.     pthread_mutex_unlock(&mutex);
  31. }
  32.  
  33. int main()
  34. {
  35.     srand(time(NULL));
  36.  
  37.     clock_t cStart = clock();
  38.  
  39.     pthread_t thread[NUMTHRDS];
  40.  
  41.     long t;
  42.     void *status;
  43.     int rc;
  44.  
  45.     pthread_mutex_init(&mutex, NULL);
  46.  
  47.     for(t=0; t<NUMTHRDS; t++)
  48.     {
  49.         rc = pthread_create(&thread[t], NULL, BusyWork, (void *)t);
  50.         if (rc)
  51.         {
  52.           printf("ERROR; return code from pthread_create() is %d\n", rc);
  53.           exit(-1);
  54.         }
  55.     }
  56.  
  57.     for(t=0; t<NUMTHRDS; t++)
  58.     {
  59.        rc = pthread_join(thread[t], &status);
  60.        if (rc)
  61.        {
  62.           printf("ERROR; return code from pthread_join() is %d\n", rc);
  63.           exit(-1);
  64.         }      
  65.     }
  66.  
  67.     double pi = 0.0;
  68.     pi = 4.0 * (globalUnutra * 1.0 / N);
  69.  
  70.     clock_t cEnd = clock();
  71.  
  72.     printf("PI = %lf, potrebno vreme: %lf\n", pi, (cEnd-cStart) * 1.0 / CLOCKS_PER_SEC);
  73.  
  74.     pthread_mutex_destroy(&mutex);
  75.     pthread_exit(NULL);
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement