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

할 수 있지만 이는 효과적으로 순차적으로 실행됩니다. 스레드는 한 번에 하나의 스레드 만 루프 본문을 실행하도록 지속적으로 임계 섹션에 들어가기를 기다리고 있습니다. 따라서 일반 직렬 루프와 동일한 성능 (동기화 오버 헤드로 인해 더 나쁠 수 있음)을 얻을 수 있습니다.

MS 문서의 예제는 새로운 최대 값이 발생한 경우에만 동기화됩니다. 이를 통해이 시점까지 모든 낮은 값을 병렬로 처리 할 수 ​​있습니다.

의견에서 제안한대로 축소 구조를 사용하십시오.