Advertisement
Pagoniusz

ptlab6

May 7th, 2015
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.72 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. typedef enum { false, true } bool;
  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 temp;
  21.         double x,y;
  22.         printf("Startuje watek %d\n",++nr_watku);
  23.         temp=nr_watku;
  24.         while(points < n)
  25.         {
  26.             bool 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",temp);
  37.         return NULL;
  38. }
  39.  
  40.  
  41. int main()
  42. {
  43.      struct timeval start, end;
  44.      srand(time(NULL));
  45.      int j;
  46.      float s;
  47.      pthread_t w[liczba_watkow];
  48.      long mtime, seconds, useconds;  
  49.      gettimeofday(&start, NULL);
  50.      printf("start:\n");
  51.            
  52.         for(j=0; j<liczba_watkow; j++)
  53.         {
  54.              pthread_create( &w[j], NULL, losuj, NULL );
  55.         }
  56.         for(j=0; j<liczba_watkow; j++)
  57.         {
  58.              pthread_join( w[j], NULL );
  59.         }      
  60.  
  61.  
  62.    
  63.  
  64.      printf("Liczba pkt. w kole wynosi: %d\n",nk);
  65.      printf("Liczba pkt. w kwadracie wynosi: %d \n",n);
  66.      s = 4. * nk / n;
  67.      printf("Liczba pi wynosi: %f\n",s);
  68.  
  69.     gettimeofday(&end, NULL);
  70.     seconds  = end.tv_sec  - start.tv_sec;
  71.     useconds = end.tv_usec - start.tv_usec;
  72.     mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;
  73.     printf("Czas: %ld milliseconds\n", mtime);
  74.     pthread_mutex_destroy(&lock);
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement