0

I'm having an issue trying to parallelize a nested loop using OpenMP - it's just demo code for playing around and getting used to.

int* myresults = new int[1000]   
#pragma omp parallel
{
    #pragma omp for 
    for(int z=0; z<=mainCount;z++)
    {
        results[n++] = myfunc(z,0); //compute something


        for(int i=0;i<=secondCount;i+=5)
        {
            results[n++]=myfunc(z,i);
        }
    }
}

My problem is the indexing of my results array. I assume since OpenMP is parallelizing the first for-loop that he is using positions of results[] twice or more because results[n++] will produce undefined behaviour (as it cannot be assured that n is incremented right), am I correct?

How can I correctly index and store my results?

1 Answer 1

1

n is incremented once for myfunc(z,0) and 1 + secondCount/5 times for myfunc(z,i). This means that n should be z * (2 + secondCount/5) at the beginning of each iteration of the outer loop. You should rewrite your code like this:

#pragma omp parallel for private(n)
for (int z = 0; z <= mainCount; z++)
{
    n = z * (2 + secondCount/5);

    results[n++] = myfunc(z, 0);

    for (int i = 0; i <= secondCount; i += 5)
        results[n++] = myfunc(z, i);
}
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.