OpenMP critical critical region

Critical section used where possible competition data access, usage: #pragma omp critical (name)(name can be omitted). To ensure that only one thread to enter.

Note: critical statement can not be nested each other

Example: In a parallel domain for task sharing domain, each thread one by one into the critical area of ​​protection, compare the current element of the relationship between the largest and replacement worth the maximum possible, so as to avoid the situation of data competition.

#include <stdio.h>
#include <omp.h>
int main()
{
    int i, max_x = -1, max_y = -1;
    int arx[] = {5, 16, 87, 65, 24, 35, 9, 33};
    int ary[] = {68, 4, 98, 43, 56, 18, 54, 11};
#pragma omp parallel for
    for (i = 0; i < 8; i++)
    {
#pragma omp critical
        if (arx[i] > max_x)
            max_x = arx[i];
#pragma omp critical
        if (ary[i] > max_y)
            max_y = ary[i];
    }
    printf("max_x = %d , max_y = %d\n", max_x, max_y);

    return 0;
}
Published 673 original articles · won praise 644 · views 380 000 +

Guess you like

Origin blog.csdn.net/zhaohaibo_/article/details/90408956