0
votes

Suppose I have an array with indices 0..n-1. Is there a way to choose which cells each thread would handle? e.g. thread 0 would handle cells 0 and 5 , thread 1 would handle cells 1 and 6 and so on..

2
two questions: why do you want that? what have you tried?stefan
Nested loops, for(off = 0; off < 5; ++off) { for(i = off; i < size; i += 5) { ... }}? (Assuming you have a typo and mean thread 1 treats 1, 6 etc.)Daniel Fischer
@stefan Because cells 0 and 5 at next iteration require cells 0 and 5 at current iteration (same for 1,6 2,7 and so on) , thus, I want to assign each thread a pair of cellsShmoopy
@DanielFischer I can't use that since n is not known at compile time.. I'm looking for something dynamicShmoopy
Note that such assignment of array elements to threads often leads to high amount of false sharing and the parallel code might not run as fast as one would expect it to do.Hristo Iliev

2 Answers

2
votes

Have you looked at the schedule clause for the parallel for?

#pragma omp for schedule(static, 1)

should implement what you want, you can experiment with the schedule clause using the following simple code:

#include<stdio.h>
#include<omp.h>

int main(){

  int i,th_id;

  #pragma omp parallel for schedule(static,1)
  for ( i = 0 ; i < 10 ; ++i){
    th_id = omp_get_thread_num();
    printf("Thread %d is on %d\n",th_id,i);
  }

}
0
votes

You can even be more explicit:

#pragma omp parallel
{
   int nth = omp_get_num_threads();
   int ith = omp_get_thread_num();
   for (int i=ith; i<n; i+=nth)
   {
      // handle cell i.
   }
}

this should do exactly what you want: thread ith handles cell ith, ith+nth, ith+2*nth, ith+3*nth and so on.