Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <pthread.h>
- #include <unistd.h>
- #include <sys/time.h>
- #define liczba_watkow 4
- typedef enum { false, true } bool;
- pthread_mutex_t lock;
- int n=100000;
- int nk;
- int points;
- int nr_watku;
- void *losuj(void *i)
- {
- int temp;
- double x,y;
- printf("Startuje watek %d\n",++nr_watku);
- temp=nr_watku;
- while(points < n)
- {
- bool a;
- x = ((double)rand() / (RAND_MAX))*2 - 1;
- y = ((double)rand() / (RAND_MAX))*2 - 1;
- a = x*x + y*y <= 1;
- pthread_mutex_lock(&lock);
- if(a)
- nk++;
- points++;
- pthread_mutex_unlock(&lock);
- }
- printf("Koniec watku %d\n",temp);
- return NULL;
- }
- int main()
- {
- struct timeval start, end;
- srand(time(NULL));
- int j;
- float s;
- pthread_t w[liczba_watkow];
- long mtime, seconds, useconds;
- gettimeofday(&start, NULL);
- printf("start:\n");
- for(j=0; j<liczba_watkow; j++)
- {
- pthread_create( &w[j], NULL, losuj, NULL );
- }
- for(j=0; j<liczba_watkow; j++)
- {
- pthread_join( w[j], NULL );
- }
- printf("Liczba pkt. w kole wynosi: %d\n",nk);
- printf("Liczba pkt. w kwadracie wynosi: %d \n",n);
- s = 4. * nk / n;
- printf("Liczba pi wynosi: %f\n",s);
- gettimeofday(&end, NULL);
- seconds = end.tv_sec - start.tv_sec;
- useconds = end.tv_usec - start.tv_usec;
- mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;
- printf("Czas: %ld milliseconds\n", mtime);
- pthread_mutex_destroy(&lock);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement