以下代码是有效的 OpenMP 并行程序吗?

Is the following code a valid OpenMP parallel program?

我正在备考,其中一个练习题是编写一段代码,在SMP计算机上实现数组所有元素的并行求和。我之前写过一些 OpenMP 程序,这些程序非常大,但没有真正利用子句和指令,我遇到了缩减子句,所以我想知道下面的部分是否是一个并行程序,因为我想知道如何相对简单的可以将程序减少到但仍保留并行化吗?

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


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

    int n = atoi(argv[1]);
    double * X;
    X = malloc(n * sizeof(double));
    for(int i = 0; i < n; i++){ X[i] = 2.0; }

    int i = 0;
    double sum = 0.0;

    omp_set_num_threads(atoi(argv[2]));

    #pragma omp parallel for private(i), shared(X) reduction(+: sum)
    for(i = 0; i < n; i++){
        sum += X[i];
    }

    printf("Sum is : %0.2f\n", sum);

    return 0;
}

为什么不 运行 它并进行测试。您也可以 运行 在您的 laptop/desktop 上使用类似的东西。 是的,此代码中的归约操作是并行的(求和计算)。 但是,将数组 X 的元素设置为 2.0 是顺序的。为了使程序真正并行,您需要 #pragma omp parallel for 而不是 for(int i = 0; i < n; i++){ X[i] = 2.0; }。否则,阿姆达尔定律将适用。

I came across the reduction clause so I was wondering if the following piece is a parallel program

来自 #pragma omp parallel 上的 OpenMP 标准:

When a thread encounters a parallel construct, a team of threads is created to execute the parallel region. The thread that encountered the parallel construct becomes the master thread of the new team, with a thread number of zero for the duration of the new parallel region. All threads in the new team, including the master thread, execute the region. Once the team is created, the number of threads in the team remains constant for the duration of that parallel region.

所以是的,它是一个并行程序,只要您在方法上明确设置它的线程数:

omp_set_num_threads(atoi(argv[2]));

大于 1。

在:

#pragma omp parallel for private(i), shared(X) reduction(+: sum)

privatei可以省略,因为在并行循环中用作index,OpenMP会将其设为private