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!

1 Answer 1

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.

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

1 Comment

Looks like you got it (+1). I defined a iterator (test2) only for the loop and assigned test = test2 and now it works coliru.stacked-crooked.com/a/d68c8801995e63e9

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.