Reputation: 93
Below is some code I made that uses pthreads that calculates an approximation of pi.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
long num_terms;
double sum = 0.0;
pthread_mutex_t sum_lock;
void* calculate_pi(void* r) {
long rank = (long) r;
double factor;
long n = num_terms / rank;
long first = n * rank;
long last = first + n;
if (first % 2 == 0) {
factor = 1.0;
} else {
factor = -1.0;
}
for (long i = first; i < last; i++, factor = -factor) {
pthread_mutex_lock(&sum_lock);
sum += factor / (2 * i + 1);
pthread_mutex_unlock(&sum_lock);
}
return NULL;
}
int main(int argc, char* argv[]) {
if (argc != 3) {
printf("Error: must have exactly 3 arguments.\n");
return 1;
}
long num_threads = strtol(argv[1], NULL, 10);
num_terms = strtol(argv[2], NULL, 10);
pthread_t* threads = malloc(num_threads * sizeof(pthread_t));
pthread_mutex_init(&sum_lock, NULL);
for (long i = 0; i < num_threads; i++) {
pthread_create(&threads[i], NULL, calculate_pi, (void*) i + 1);
}
for (long i = 0; i < num_threads; i++) {
pthread_join(threads[i], NULL);
}
sum = sum * 4.0;
printf("Estimated value of pi: %f\n", sum);
pthread_mutex_destroy(&sum_lock);
free(threads);
return 0;
}
Normally, when I run this program with the sample arguments 4 and 1000000, it's supposed to print out this:
Estimated value of pi: 3.141593
But instead, it prints out this, which isn't even close to the value of pi:
Estimated value of pi: -0.000001
Can you figure out what's wrong?
Upvotes: 0
Views: 76