Using OpenMP with C++11 range-based for loops?

匿名 (未验证) 提交于 2019-12-03 02:14:01

问题:

Is there any counter-indication to doing this ? Or is the behavior well specified?

#pragma omp parallel for for(auto x : stl_container) {    ... } 

Because it seems that OpenMP specification is only valid for c++98 but I guess there might be more incompatibilities due to C++11 threads, which are not used here. I wanted to be sure, still.

回答1:

The OpenMP 4.0 specification was finalised and published several days ago here. It still mandates that parallel loops should be in the canonical form (§2.6, p.51):

for (init-expr; test-expr; incr-expr) structured-block

The standard allows for containers that provide random-access iterators to be used in all of the expressions, e.g.:

#pragma omp parallel for for (it = v.begin(); it < v.end(); it++) {    ... } 

If you still insist on using the C++11 syntactic sugar, and if it takes a (comparatively) lot of time to process each element of stl_container, then you could use the single-producer tasking pattern:

#pragma omp parallel {    #pragma omp single    {       for (auto x : stl_container)       {          #pragma omp task          {             // Do something with x, e.g.             compute(x);          }       }    } } 

Tasking induces certain overhead so it would make no sense to use this pattern if compute(x); takes very little time to complete.



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