11
11
#include <stdio.h>
12
12
#include <math.h>
13
13
#include <stdlib.h>
14
- #include <time .h>
14
+ #include <limits .h>
15
15
#include <semaphore.h>
16
+ #include <time.h>
16
17
17
- #define n_threads 4 // Num of threads
18
- #define n_points 100000 // Num of iterations
19
-
20
- pthread_t tid [n_threads ];
21
- sem_t mutex ;
18
+ #define n_threads 16 /* Num of threads */
19
+ #define n_points 100000 /* Num of iterations */
22
20
23
- int count = 0 ;
24
- double pi ;
25
21
int iter_per_thread = n_points / n_threads ;
26
22
23
+ pthread_t tid [n_threads ]; /* Threads IDs */
24
+ sem_t mutex ; /* Sync bit */
25
+
26
+ int count = 0 ; /* Total points inside the circle */
27
+ double pi = 0 ; /* Variable for calculated pi vavlue */
28
+
29
+ unsigned int seed = 676767676 ; /* Seed for random number */
30
+
27
31
28
32
/*
29
33
* Function: generateRandom
30
34
* --------------------
31
35
* Generates a random decimal number between 0 and 1
32
36
*
33
- * Taken from https://stackoverflow.com/a/3067387
37
+ * Random number generator with linear congruential generator
38
+ *
39
+ * Taken from “Numerical Recipes” by William H. Press, Chapter 7: Random Numbers
34
40
*
35
41
* returns: random double
36
42
*/
37
43
double generateRandom ()
38
44
{
39
- srand ( time ( NULL ) ) ;
40
- return ( double ) rand () / RAND_MAX ;
45
+ seed = seed * 1103515245 + 123456 ;
46
+ return seed / ( double ) UINT_MAX ;
41
47
}
42
48
43
49
/*
@@ -51,24 +57,24 @@ void *calculatePi(void *arg)
51
57
{
52
58
for (int i = 0 ; i < iter_per_thread ; i ++ )
53
59
{
54
- sem_wait (& mutex );
55
60
double x = generateRandom ();
56
61
double y = generateRandom ();
57
62
58
63
double result = ( x * x ) + ( y * y );
59
64
60
65
if (result <= 1 )
61
66
{
62
- sem_post (& mutex );
67
+ sem_wait (& mutex );
63
68
count ++ ;
69
+ sem_post (& mutex );
64
70
}
65
71
}
66
72
return NULL ;
67
73
}
68
74
69
75
int main ()
70
76
{
71
-
77
+ clock_t begin = clock ();
72
78
sem_init (& mutex , 0 , 1 ); /* Initialize semaphore */
73
79
74
80
/* Create threads */
@@ -83,9 +89,11 @@ int main()
83
89
pthread_join (tid [i ], NULL );
84
90
}
85
91
86
- pi = (double ) count / n_points * 4 ;
92
+ pi = ( ( double )count / ( double ) n_points ) * 4.0 ;
87
93
88
- printf ("# of trials = %d , estimate of pi is %1.16f AND an absolute error of %g\n" , n_points , pi , fabs (pi - M_PI ));
89
-
94
+ printf ("# of trials = %d, estimate of pi is %1.16f and an absolute error of %g\n" , n_points , pi , fabs (pi - M_PI ));
95
+ clock_t end = clock ();
96
+ double time_spent = (double )(end - begin ) / CLOCKS_PER_SEC ;
97
+ printf ("Elapsed time: %4f seconds || Threads: %d threads\n" , time_spent , n_threads );
90
98
return 0 ;
91
99
}
0 commit comments