1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
| #include <stdio.h> #include <stdlib.h> #include <math.h> #include <pthread.h> #include <semaphore.h> #include <sys/time.h>
#define GET_TIME(now) \ { \ struct timeval t; \ gettimeofday(&t, NULL); \ now = t.tv_sec + t.tv_usec / 1000000.0; \ }
const int MAX_THREADS = 1024;
long thread_count; long long n; double sum;
sem_t sem;
void *Thread_sum(void *rank);
void Get_args(int argc, char *argv[]); void Usage(char *prog_name); double Serial_pi(long long n);
int main(int argc, char *argv[]) { long thread; pthread_t *thread_handles; double start, finish, elapsed;
n = 10000000000; thread_count = 4;
thread_handles = (pthread_t *)malloc(thread_count * sizeof(pthread_t)); sem_init(&sem, 0, 1); sum = 0.0;
GET_TIME(start); for (thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], NULL, Thread_sum, (void *)thread);
for (thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], NULL); GET_TIME(finish); elapsed = finish - start;
sum = 4.0 * sum; printf("With n = %lld terms,\n", n); printf(" Our estimate of pi = %.15f\n", sum); printf("The elapsed time is %e seconds\n", elapsed); GET_TIME(start); sum = Serial_pi(n); GET_TIME(finish); elapsed = finish - start; printf(" Single thread est = %.15f\n", sum); printf("The elapsed time is %e seconds\n", elapsed); printf(" pi = %.15f\n", 4.0 * atan(1.0));
sem_destroy(&sem); free(thread_handles); return 0; }
void *Thread_sum(void *rank) { long my_rank = (long long)rank; double my_sum = 0.0;
double factor = 1; long long max_size = 0; if (my_rank == 3) { max_size = n; } else { max_size = my_rank * n / 4 + n / 4; } for (long long i = my_rank * n / 4; i < max_size; i++, factor = -factor) { my_sum += factor / (2 * (i + my_rank) + 1); }
sem_wait(&sem); sum += my_sum; sem_post(&sem);
return NULL; }
double Serial_pi(long long n) { double sum = 0.0; long long i; double factor = 1.0;
for (i = 0; i < n; i++, factor = -factor) { sum += factor / (2 * i + 1); } return 4.0 * sum;
}
void Get_args(int argc, char *argv[]) { if (argc != 3) Usage(argv[0]); thread_count = strtol(argv[1], NULL, 10); if (thread_count <= 0 || thread_count > MAX_THREADS) Usage(argv[0]); n = strtoll(argv[2], NULL, 10); if (n <= 0) Usage(argv[0]); }
void Usage(char *prog_name) { fprintf(stderr, "usage: %s <number of threads> <n>\n", prog_name); fprintf(stderr, " n is the number of terms and should be >= 1\n"); fprintf(stderr, " n should be evenly divisible by the number of threads\n"); exit(0); }
|