0

I'm tryng to add all the members of an array using openmp this way

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[])
{
    int v[] ={1,2,3,4,5,6,7,8,9};
    int sum = 0;
    #pragma omp parallel private(v, sum)
    {
        #pragma reduction(+: sum)
        {
            for (int i = 0; i < sizeof(v)/sizeof(int); i++){
                sum += v[i];
            }

        }
    }
    printf("%d\n",sum);
}

But when I print sum the result is 0

5
  • I've changed the question Commented Oct 20, 2018 at 17:14
  • It's printing the sum as 45 Commented Oct 20, 2018 at 17:27
  • @suvojit_007 no its printing a diffrent result every execution Commented Oct 20, 2018 at 17:28
  • @AFS I have exected your code several times but it gave me the same result every time Commented Oct 20, 2018 at 17:30
  • @suvojit_007 can you share your compilation command? Commented Oct 20, 2018 at 17:31

1 Answer 1

1

You are very confused about data-sharing attributes and work-sharing for OpenMP. This answer does not attempt to properly teach them to you, but only give you a concise specific example.

Your code does not make any sense and does not compile.

You do not need multiple regions or such, and there are only two variables. v - which is defined outside, is read by all and must be shared - which it implicitly is because it is defined outside. Then there is sum, which is a reduction variable.

Further, you need to apply worksharing (for) to the loop. So in the end it looks like this:

int v[] ={1,2,3,4,5,6,7,8,9};
int sum = 0;
#pragma omp parallel for reduction(+: sum)
for (int i = 0; i < sizeof(v)/sizeof(int); i++){
    sum += v[i];
}
printf("%d\n",sum);

Note there are private variables in this example. Private variables are very dangerous because they are uninitialized inside the parallel region, simply don't use them explicitly. If you need something local, declare it inside the parallel region.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.