c++ openmp for循环在循环执行期间的最大减少值

标签 c++ multithreading max openmp reduction

在并行 for 循环中计算最大减少量时,在循环执行期间的中间时间,最大减少量变量的值是多少?它是仅针对特定线程的最大值还是所有线程的最大值?

我问的原因是我想使用循环内的当前最大值来执行计算,我希望它是所有线程的当前最大值,而不仅仅是执行循环的线程。

例如:

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

int main(int argc, char *argv[]) {

    double randomarray[10];
    //initialize the random array

    double outputarray[10];
    double currentmax = 0;

    #pragma omp parallel for reduction(max:currentmax)
    for( i=0;i<10; i++) {

        if(randomarray[i] > currentmax)
        {
            currentmax = randomarray[i];   
        }

        output[i]=randomarray[i]/currentmax;
        // is this current max for the currently 
        // executing thread or all threads?
    }

}

最佳答案

reduction 变量的值在使用 reduction close 的构造中未定义,并且在线程之间有所不同。每个线程都有变量的私有(private)拷贝。您将不得不重新考虑您的并行化。

来自 OpenMP 4 规范:

For parallel and worksharing constructs, a private copy of each list item is created, one for each implicit task, as if the private clause had been used. ... The private copy is then initialized as specified above. At the end of the region for which the reduction clause was specified, the original list item is updated by combining its original value with the final value of each of the private copies, using the combiner of the specified reduction-identifier.

关于c++ openmp for循环在循环执行期间的最大减少值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26664820/

相关文章:

c++ - 为什么没有像 pthread_mutex_t & std::mutex 那样的 std::等价于 pthread_spinlock_t?

SQL - 选择所有行并将列值替换为带有标识符的最大列值

excel - 限制公式中的单元格值

c++ - 如何编写函数和成员函数的包装器,在包装函数之前和之后执行一些代码?

c++ - Visual Studio 2013 : How to open basic C file

c# - 使用参数创建新线程时索引超出范围?

c++ - opencv cv::max 行为意外

c++ - (如何)我可以使用 LLVM 机器代码分析器预测代码片段的运行时间吗?

c++ - STL accumulate() 函数

python - 如何评估 python 模块是否线程安全?