2

I've been trying to parallelize a C program using OpenMP, and it's like this:

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

int test, result;
#pragma omp threadprivate(test, result)

void add(void)
{
    result = result + test;
}

int main(void)
{
    int i;
#pragma omp parallel for private(i) 
    for (test = 0; test < 5; test++) {
        result = 0;
        for (i = 1; i < 100; i++) {
            add();
        }
        printf("Result in %dth test is: %d\n", test, result);
    } //End of parallel region
    return 0;
}

Compile and run it sequentially, I get the following output:

Result in 0th test is: 0
Result in 1th test is: 99
Result in 2th test is: 198
Result in 3th test is: 297
Result in 4th test is: 396

However, when I compile with -fopenmp and run it, I got all zeros:

Result in 0th test is: 0
Result in 1th test is: 0
Result in 3th test is: 0
Result in 4th test is: 0
Result in 2th test is: 0

Can anyone tell me what I did wrong in my program? I'm new in openMP. Thanks!

Devavrata
  • 1,785
  • 17
  • 30
Youkee
  • 23
  • 4

1 Answers1

3

Your program is not conforming, and yields undefined behavior. In particular if you check the latest standard you can find in section 2.7.1 the following restriction for the loop construct:

  • The loop iteration variable may not appear in a threadprivate directive

In your case what is likely to happen is a name clash between two variables named test: one should be a private int variable created for the loop iteration while the other is the global variable declared as threadprivate. But again, being undefined behavior, anything may happen.

Community
  • 1
  • 1
Massimiliano
  • 7,842
  • 2
  • 47
  • 62
  • 1
    Looks like you got it (+1). I defined a iterator (`test2`) only for the loop and assigned `test = test2` and now it works http://coliru.stacked-crooked.com/a/d68c8801995e63e9 – Z boson May 04 '14 at 15:11