c++ - openMP 嵌套并行 for 循环与内部并行 for

如果我像这样使用嵌套的并行循环:

#pragma omp parallel for schedule(dynamic,1)
for (int x = 0; x < x_max; ++x) {
    #pragma omp parallel for schedule(dynamic,1)
    for (int y = 0; y < y_max; ++y) { 
    //parallelize this code here
   }
//IMPORTANT: no code in here
}

这是否等同于:

for (int x = 0; x < x_max; ++x) {
    #pragma omp parallel for schedule(dynamic,1)
    for (int y = 0; y < y_max; ++y) { 
    //parallelize this code here
   }
//IMPORTANT: no code in here
}

除了创建新任务之外,外部并行是否可以做任何事情?

最佳答案

如果您的编译器支持 OpenMP 3.0,则可以使用 collapse 子句:

#pragma omp parallel for schedule(dynamic,1) collapse(2)
for (int x = 0; x < x_max; ++x) {
    for (int y = 0; y < y_max; ++y) { 
    //parallelize this code here
    }
//IMPORTANT: no code in here
}

如果不支持(例如仅支持 OpenMP 2.5),有一个简单的解决方法:

#pragma omp parallel for schedule(dynamic,1)
for (int xy = 0; xy < x_max*y_max; ++xy) {
    int x = xy / y_max;
    int y = xy % y_max;
    //parallelize this code here
}

您可以使用 omp_set_nested(1); 启用嵌套并行性,并且您的嵌套 omp parallel for 代码将起作用,但这可能不是最好的主意。

顺便问一下,为什么是动态调度?是否每次循环迭代都在非常量时间内进行评估?

https://stackoverflow.com/questions/10540760/

相关文章:

c++ - 为什么 std::get() 不能用于获取 vector 的成员?

c++ - 如何找到当前的系统时区?

c++ - 在构造函数中调用类成员的构造函数

c++ - 为什么 PRIu64 在此代码中不起作用?

c++ - Emacs - 覆盖缩进

c++ - 不能在数组上使用 .begin() 或 .end()

c++ - 了解 double 到 int64_t 的转换

c++ - 在 C++ 中,是否可以获取函数的返回类型以便在不调用该函数的情况下声明一个变量?

c++ - OpenCV:获取 3 channel RGB 图像,拆分 channel 并仅使用 R

c++ - 在 C/C++ 中从 TCP 套接字读取的正确方法是什么?