Advertisement
Pagoniusz

Untitled

May 7th, 2015
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.73 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <pthread.h>
  5. #include <unistd.h>
  6. #include <sys/time.h>
  7.  
  8. #define liczba_watkow 4
  9.  
  10. pthread_mutex_t lock;
  11. int n=100000;
  12. int nk;
  13. int points;
  14. int nr_watku;
  15.      
  16.  
  17. void *losuj(void *i)
  18. {      
  19.  
  20.     int nr_watku2;
  21.         double x,y;
  22.         printf("Startuje watek %d\n",++nr_watku);
  23.         nr_watku2=nr_watku;
  24.         while(points < n)
  25.         {
  26.             int a;
  27.             x = ((double)rand() / (RAND_MAX))*2 - 1;
  28.             y = ((double)rand() / (RAND_MAX))*2 - 1;
  29.             a = x*x + y*y <= 1;
  30.             pthread_mutex_lock(&lock);
  31.             if(a)
  32.                 nk++;
  33.             points++;
  34.             pthread_mutex_unlock(&lock);
  35.         }
  36.         printf("Koniec watku %d\n",nr_watku2);
  37.         return NULL;
  38. }
  39.  
  40.  
  41. int main()
  42. {
  43.      struct timeval start, end;
  44.      srand(time(NULL));
  45.      double x,y;
  46.      int i,j;
  47.      float s;
  48.      pthread_t w[liczba_watkow];
  49.      nk=0;
  50.      long mtime, seconds, useconds;  
  51.      gettimeofday(&start, NULL);
  52.      printf("start:\n");
  53.            
  54.         for(j=0; j<liczba_watkow; j++)
  55.         {
  56.              pthread_create( &w[j], NULL, losuj, NULL );
  57.         }
  58.         for(j=0; j<liczba_watkow; j++)
  59.         {
  60.              pthread_join( w[j], NULL );
  61.         }      
  62.  
  63.  
  64.    
  65.  
  66.      printf("Liczba pkt. w kole wynosi: %d\n",nk);
  67.      printf("Liczba pkt. w kwadracie wynosi: %d \n",n);
  68.      s = 4. * nk / n;
  69.      printf("Liczba pi wynosi: %f\n",s);
  70.  
  71.     gettimeofday(&end, NULL);
  72.     seconds  = end.tv_sec  - start.tv_sec;
  73.     useconds = end.tv_usec - start.tv_usec;
  74.     mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;
  75.     printf("Czas: %ld milliseconds\n", mtime);
  76.     pthread_mutex_destroy(&lock);
  77.      return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement