【OpenMP】#pragma omp critical 子句

#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

你可能感兴趣的:(并行计算)