OpenMP - for loop thread assignment

半世苍凉 提交于 2019-12-08 09:23:55

问题


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..


回答1:


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.




回答2:


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

}


来源:https://stackoverflow.com/questions/13663750/openmp-for-loop-thread-assignment

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!