Below I have attached my code. The problem I am having is that I do not think it is properly computing the sum. It seems as if its missing a number or something along those lines. The program is supposed to read an input number, n, which must be a multiple of 3, and use threads to compute the sum of the square roots. If anyone could point me in the right direction, that would be great. Thank you.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

static double sum=0;
pthread_mutex_t mutex1;
pthread_mutex_init(mutex1);

void sroot(int r)
 {
  int k=1;
  pthread_mutex_lock(&mutex1);
  for(k;k<r;k++)
    sum=sum+sqrt(k);
  pthread_mutex_unlock(&mutex1);
  return 0;
 }

int main(int argc, char *argv[])
 {
  int n;
  n=atoi(argv[1]);
  int a = n/3;
  sroot(a); // Computes sum for 1 to n/3
  pthread_t tid, tid1;
  pthread_create(&tid1,NULL,sroot,(2*n)/3); // Computes sum for (n/3)+1 to 2n/3
  pthread_join(tid1, NULL); // Wait for thread 1 to end
  pthread_create(&tid2,NULL,sroot,n); // Computes sum for (2n/3)+1 to n
  //pthread_join(tid1, NULL); // Wait for thread 1 to end
  pthread_join(tid2, NULL); // Wait for thread 2 to end
  printf("%f\n",sum);    // Print result
  return 0;
 }

> I do not think it is properly computing the sum.

Yes. But it has nothing to do with threads. The way you joining the threads means that nothing is running concurrently. Essentially you are calling sroot 3 times in a row, as in

sum = sroot(n/3) + sroot(2*n/3) + sroot(n)

and sroot calculates a sum of square roots from ... umm ... from what to what?

It calculates the sum of the roots from 1 to the user inputted n value.

It calculates the sum of the roots from 1 to the user inputted n value.

I should probably be more clear. The user input value, n, is assumed to be a multiple of 3, making it able to be easily divided among 3 threads. 3 partial sums should be added together, and the final sum printed. This runs fine, but the final sum printed is wrong.

Edited 5 Years Ago by NV43: n/a

Consider n==3.
The first call yields 1.
The second one yields 1+sqrt(2)
The third yields 1+sqrt(2)+sqrt(3)
Finally, you add them all together. Is that what you want?

The way it should work is as follows. If the user enters a number, say 3, the program would do the following:

sqrt(1)+sqrt(2)+sqrt(3)

User enters 6:

sqrt(1)+sqrt(2)+sqrt(3)+sqrt(4)+sqrt(5)+sqrt(6)

Each thread handles a third of the computing, then the sum of their partial sums is printed.

Do you see the difference between "should work" and "does"? The loop in sroot() starts with k = 1 no matter what. Only the final value is passed. You must pass an initial value as well.

This article has been dead for over six months. Start a new discussion instead.