Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #include<time.h>
- #include<math.h>
- #include <pthread.h>
- #define NUMTHRDS 4
- #define N 100000000
- pthread_mutex_t mutex;
- double globalUnutra;
- void *BusyWork(void*arg)
- {
- long tid = (long)arg;
- int i;
- double x, y;
- double unutra = 0.0;
- for (i=tid*N/NUMTHRDS; i<(tid*N/NUMTHRDS)+N/NUMTHRDS; i++)
- {
- x = rand() * 1.0 / RAND_MAX;
- y = rand() * 1.0 / RAND_MAX;
- if((x*x + y*y) <= 1.0)
- unutra++;
- }
- pthread_mutex_lock(&mutex);
- globalUnutra += unutra;
- pthread_mutex_unlock(&mutex);
- }
- int main()
- {
- srand(time(NULL));
- clock_t cStart = clock();
- pthread_t thread[NUMTHRDS];
- long t;
- void *status;
- int rc;
- pthread_mutex_init(&mutex, NULL);
- for(t=0; t<NUMTHRDS; t++)
- {
- rc = pthread_create(&thread[t], NULL, BusyWork, (void *)t);
- if (rc)
- {
- printf("ERROR; return code from pthread_create() is %d\n", rc);
- exit(-1);
- }
- }
- for(t=0; t<NUMTHRDS; t++)
- {
- rc = pthread_join(thread[t], &status);
- if (rc)
- {
- printf("ERROR; return code from pthread_join() is %d\n", rc);
- exit(-1);
- }
- }
- double pi = 0.0;
- pi = 4.0 * (globalUnutra * 1.0 / N);
- clock_t cEnd = clock();
- printf("PI = %lf, potrebno vreme: %lf\n", pi, (cEnd-cStart) * 1.0 / CLOCKS_PER_SEC);
- pthread_mutex_destroy(&mutex);
- pthread_exit(NULL);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement