c++ - 减少 OpenMP 中的数组

标签 c++ multithreading parallel-processing openmp reduction

我正在尝试并行化以下程序,但不知道如何减少数组。我知道这样做是不可能的,但有其他选择吗?谢谢。 (我在 m 上添加了减法,这是错误的,但想就如何做得到建议。)

#include <iostream>
#include <stdio.h>
#include <time.h>
#include <omp.h>
using namespace std;

int main ()
{
  int A [] = {84, 30, 95, 94, 36, 73, 52, 23, 2, 13};
  int S [10];

  time_t start_time = time(NULL);
  #pragma omp parallel for private(m) reduction(+:m)
  for (int n=0 ; n<10 ; ++n ){
    for (int m=0; m<=n; ++m){
      S[n] += A[m];
    }
  }
  time_t end_time = time(NULL);
  cout << end_time-start_time;

  return 0;
}

最佳答案

是的,可以使用 OpenMP 进行数组缩减。在 Fortran 中,它甚至为此进行了构造。在 C/C++ 中,你必须自己做。这里有两种方法。

第一种方法为每个线程制作私有(private)版本的S,并行填充,然后在临界区合并到S中(见下面的代码) .第二种方法创建一个维度为 10*nthreads 的数组。并行填充此数组,然后将其合并到 S 中,而不使用临界区。第二种方法要复杂得多,如果您不小心,可能会出现缓存问题,尤其是在多插槽系统上。欲了解更多详情,请参阅 Fill histograms (array reduction) in parallel with OpenMP without using a critical section

第一种方法

int A [] = {84, 30, 95, 94, 36, 73, 52, 23, 2, 13};
int S [10] = {0};
#pragma omp parallel
{
    int S_private[10] = {0};
    #pragma omp for
    for (int n=0 ; n<10 ; ++n ) {
        for (int m=0; m<=n; ++m){
            S_private[n] += A[m];
        }
    }
    #pragma omp critical
    {
        for(int n=0; n<10; ++n) {
            S[n] += S_private[n];
        }
    }
}

第二种方法

int A [] = {84, 30, 95, 94, 36, 73, 52, 23, 2, 13};
int S [10] = {0};
int *S_private;
#pragma omp parallel
{
    const int nthreads = omp_get_num_threads();
    const int ithread = omp_get_thread_num();

    #pragma omp single 
    {
        S_private = new int[10*nthreads];
        for(int i=0; i<(10*nthreads); i++) S_private[i] = 0;
    }
    #pragma omp for
    for (int n=0 ; n<10 ; ++n )
    {
        for (int m=0; m<=n; ++m){
            S_private[ithread*10+n] += A[m];
        }
    }
    #pragma omp for
    for(int i=0; i<10; i++) {
        for(int t=0; t<nthreads; t++) {
            S[i] += S_private[10*t + i];
        }
    }
}
delete[] S_private;

关于c++ - 减少 OpenMP 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20413995/

相关文章:

java - Java中的阻塞队列

c - 如何在没有任何非标准库的情况下在 C 中进行多处理

c++ - 为什么并行版本更慢?

c++ - 在这种情况下,我们可以使用 "signed"到 "unsigned"的技巧来保存一次比较吗?

c++ - 从整数数组在 gtkmm 中显示图像

c++ - while循环中的while循环,两个条件如何工作?

c++ - 迭代器库的正面和背面提案

java - 停止 Java 线程的安全方法

c# - TPL 能否在多个线程上运行任务?

algorithm - 任何分布式并行树搜索算法建议?