[OpenMP] #pragma omp critical 자구

6798 단어 병렬 계산
4#pragma omp critical 자구의 역할은 한 구역이 최대 한 라인만 안에서 운행할 수 있도록 제한하는 것이다. 이것이 바로 임계구역이다.
우리는 최대치를 구하는 프로그램을 예로 들었다
#include 
#include 

int main(){
    int a[10] = {42,134,234,3234,14134,2345,3236,1214,345,1234};
    int max = 0;
    int i;
    omp_set_num_threads(10);
    #pragma omp parallel for
    for(i = 0; i < 10; i++){
        std::cout << "thread: " << omp_get_thread_num() << ' ';
        std::cout << "num: "<< a[i] << std::endl;
        #pragma omp critical
        {   
            std::cout << "now critical thread: " << omp_get_thread_num() << std::endl;
            if(max < a[i])
                max = a[i];
        }
    }
    std::cout <<  "max = " << max << std::endl;
}

출력 결과1:
thread: 1 num: 134 now critical thread: 1 thread: 6 num: 3236 now critical thread: 6 thread: 5 num: 2345 now critical thread: 5 thread: 7 num: 1214 now critical thread: 7 thread: 4 num: 14134 now critical thread: 4 thread: 8 num: 345 now critical thread: 8 thread: 9 num: 1234 now critical thread: 9 thread: 3 num: 3234 now critical thread: 3 thread: 2 num: 234 now critical thread: 2 thread: 0 num: 42 now critical thread: 0 max = 14134
출력 결과2
thread: 0 num: 42 now critical thread: 0 thread: 7 num: 1214 now critical thread: 7 thread: 8 num: 345 now critical thread: 8 thread: 9 num: 1234 now critical thread: 9 thread: 6 num: 3236 now critical thread: 6 thread: 5 num: 2345 now critical thread: 5 thread: 4 num: 14134 now critical thread: 4 thread: 3 num: 3234 now critical thread: 3 thread: 2 num: 234 now critical thread: 2 thread: 1 num: 134 now critical thread: 1 max = 14134
결과 출력3:
thread: 0 num: 42 now critical thread: 0 thread: 7 num: 1214 now critical thread: 7 thread: 8 num: 345 now critical thread: 8 thread: 6 num: 3236 now critical thread: 6 thread: 5 num: 2345 now critical thread: 5 thread: 9 num: 1234 now critical thread: 9 thread: 4 num: 14134 now critical thread: 4 thread: 3 num: 3234 now critical thread: 3 thread: 2 num: 234 now critical thread: 2 thread: 1 num: 134 now critical thread: 1 max = 14134

좋은 웹페이지 즐겨찾기