openmpクリティカル

Aug 19 2020

この質問に続いて、以下のコードについて(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 cos_theta Aug 19 2020 at 16:53

次のことができます、しかし、これは効果的に順次実行につながります。スレッドは、一度に1つのスレッドのみがループ本体を実行するように、クリティカルセクションに入るのを常に待機しています。したがって、単純なシリアルループと同じパフォーマンスが得られます(同期のオーバーヘッドが原因でさらに悪化する可能性があります)。

MSドキュメントの例は、新しい最大値が検出された場合にのみ同期します。これにより、この時点までのすべての低い値を並行して処理できます。

コメントで示唆されているように、リダクションコンストラクトを使用します。