For computing the value of
,
1 #include <pthread.h>
2 #include <stdlib.h>
3
4 #define MAX_THREADS 512
5 void *compute_pi (void *);
6
7 int total_hits, total_misses, hits[MAX_THREADS],
8 sample_points, sample_points_per_thread, num_threads;
9
10 main() {
11 int i;
12 pthread_t p_threads[MAX_THREADS];
13 pthread_attr_t attr;
14 double computed_pi;
15 double time_start, time_end;
16 struct timeval tv;
17 struct timezone tz;
18
19 pthread_attr_init (&attr);
20 pthread_attr_setscope (&attr,PTHREAD_SCOPE_SYSTEM);
21 printf("Enter number of sample points: ");
22 scanf("%d", &sample_points);
23 printf("Enter number of threads: ");
24 scanf("%d", &num_threads);
25
26 gettimeofday(&tv, &tz);
27 time_start = (double)tv.tv_sec +
28 (double)tv.tv_usec / 1000000.0;
29
30 total_hits = 0;
31 sample_points_per_thread = sample_points / num_threads;
32 for (i=0; i< num_threads; i++) {
33 hits[i] = i;
34 pthread_create(&p_threads[i], &attr, compute_pi,
35 (void *) &hits[i]);
36 }
37 for (i=0; i< num_threads; i++) {
38 pthread_join(p_threads[i], NULL);
39 total_hits += hits[i];
40 }
41 computed_pi = 4.0*(double) total_hits /
42 ((double)(sample_points));
43 gettimeofday(&tv, &tz);
44 time_end = (double)tv.tv_sec +
45 (double)tv.tv_usec / 1000000.0;
46
47 printf("Computed PI = %lf\n", computed_pi);
48 printf(" %lf\n", time_end - time_start);
49 }
50
51 void *compute_pi (void *s) {
52 int seed, i, *hit_pointer;
53 double rand_no_x, rand_no_y;
54 int local_hits;
55
56 hit_pointer = (int *) s;
57 seed = *hit_pointer;
58 local_hits = 0;
59 for (i = 0; i < sample_points_per_thread; i++) {
60 rand_no_x =(double)(rand_r(&seed))/(double)((2<<14)-1);
61 rand_no_y =(double)(rand_r(&seed))/(double)((2<<14)-1);
62 if (((rand_no_x - 0.5) * (rand_no_x - 0.5) +
63 (rand_no_y - 0.5) * (rand_no_y - 0.5)) < 0.25)
64 local_hits ++;
65 seed *= i;
66 }
67 *hit_pointer = local_hits;
68 pthread_exit(0);
69 }