0

I have simple program:

int index;
unsigned int count = 0;

#pragma omp parallel for
for (index = 0; index < 10000; index++)
{
    count++;
}

Problem is that I think count should be equal to 10000. But instead it is usually somewhere around 5000. In about 10% it is equal to 10000.

What is going on here?

7
  • 1
    count++ is not an atomic operation Commented Sep 4, 2016 at 13:05
  • Thanks after added #pragma omp atomic it worked Commented Sep 4, 2016 at 13:07
  • But then, the performance of this loop drops down Commented Sep 4, 2016 at 13:09
  • Is there way to do this faster? Commented Sep 4, 2016 at 13:10
  • 3
    count++ protected by atomic is one well-trodden path to writing serial programs with the overhead of OpenMP. Don't follow that path. Instead, learn how to use OpenMP's reduction variables. You'll find enough to get you started by searching here on SO. Commented Sep 4, 2016 at 13:32

1 Answer 1

5

As suggested in comments, you need reduction directive:

int index;
unsigned int count = 0;

#pragma omp parallel for reduction(+:count)
for (index = 0; index < 10000; index++)
{
    count++;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I wouldn't say need probably although this is a way to fix the issue.

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.