I am using the pthread
library to make a program to find the accurate value of pi with Leibniz formula. I am working on shared resource here. My multithreaded function looks like this:
void *Leibniz(void *vars)
{
struct variables *val = (struct variables *)vars;
int startLimit = val->start;
int endLimit = val->end;
int i;
for (i = startLimit; i <= endLimit; i++)
{
pthread_mutex_lock(&mutex);
sum += (pow(-1, i) / ((2 * i) + 1));
pthread_mutex_unlock(&mutex);
}
}
When I run the program with N
iterations and 1 thread, I get the correct output in about 4.5 seconds average. When I run the same program with two threads, it takes around 18 seconds. I have to use multithreading to make the program faster but the exact opposite is happening. Can anyone explain why?