openmp 关键

计算科学 并行计算
2021-11-29 14:57:12

这个问题之后,对于下面的代码(来自 MS OpenMP 文档示例

// omp_critical.cpp
// compile with: /openmp
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

#define SIZE 10

int main()
{
    int i;
    int max;
    int a[SIZE];

    for (i = 0; i < SIZE; i++)
    {
        a[i] = rand();
        printf_s("%d\n", a[i]);
    }

    max = a[0];
    #pragma omp parallel for num_threads(4)
    for (i = 1; i < SIZE; i++)
    {
        if (a[i] > max)
        {
            #pragma omp critical
            {
                // compare a[i] and max again because max
                // could have been changed by another thread after
                // the comparison outside the critical section
                if (a[i] > max)
                    max = a[i];
            }
        }
    }

    printf_s("max = %d\n", max);
}

如果测试并执行,我可以移除外部吗

max = a[0];
#pragma omp parallel for num_threads(4)
for (i = 1; i < SIZE; i++)
{
    #pragma omp critical
    {
        // compare a[i] and max again because max
        // could have been changed by another thread after
        // the comparison outside the critical section
        if (a[i] > max)
            max = a[i];
    }
}
1个回答

您可以,但这实际上会导致顺序执行。线程一直在等待进入临界区,因此一次只有一个线程执行循环体。因此,您可以获得与普通串行循环相同的性能(可能由于同步开销而更差)。

MS 文档中的示例仅在遇到新的最大值时才会同步。这允许并行处理到目前为止的所有较低值。

正如评论中所建议的,使用归约结构。