Question

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!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top