简体   繁体   中英

OpenMP specify thread number of a for loop iteration

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?

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 .

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,...);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM