2

I'm using the following command to parallelize a single loop over the available threads of the program:

#pragma omp parallel for num_threads(threads)
for(long i = 0; i < threads; i++)
{
    array[i] = calculateStuff(i,...);
}

For technical reasons, I would like to guarantee that thread number 0 executes i=0, and thread number 1 executes i=1. In other words, I want always i=omp_get_thread_num(). Is this possible?

2 Answers 2

5

Using a loop is a waste of resources in that particular case. Simply use omp_get_thread_num():

#include <omp.h>

#pragma omp parallel num_threads(threads)
{
    int i = omp_get_thread_num();
    array[i] = calculateStuff(i,...);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the hint. I'm gonna do this, but I can't choose this as correct answer as this doesn't answer the question.
It's not a an answer but more a suggestion to improve your code. Sometimes I wish that comments on Stack Overflow could be a bit more elaborate when it comes to formatting.
4

Try

#pragma omp parallel for num_threads(threads) schedule(static,1)

Now that @Hristo Iliev has turned up I'm 100% confident that the OpenMP standard requires the static schedule to assign iteration 0 to thread 0, 1 to 1, etc.

Try it and let us know how you get on.

Then again

#pragma omp parallel for num_threads(threads) schedule(dynamic,1)

ought to work too, since you only have as many iterations as you have threads. It's possible though that if thread 0 finishes its work before thread n starts then thread 0 will grab iteration n.

2 Comments

I think you're right. Apparently openmp does that by default. I had a mistake in my program that made me not see this. Thank you.
§2.7.1 Loop Construct: "When schedule(static, chunk_size) is specified, iterations are divided into chunks of size chunk_size, and the chunks are assigned to the threads in the team in a round-robin fashion in the order of the thread number." I.e. the standard does require it.

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.