How to use OpenMP for nested loops in a while loop?

I recently became familiar with OpenMP and concurrent programming, and I have some problems using it.

I want to implement OpenMP in the following code so that it works faster.

int m = 101;
double e = 10;

double A[m][m], B[m][m];
for (int x=0; x<m; x++){
    for (int y=0; y<m; y++){
        A[x][y] = 0;
        B[x][y] = 1;
    }
}

while (e >= 0.0001){
    for (int x=0; x<m; x++){
        for (int y=0; y<m; y++){
            A[x][y] = 0.25*(B[x][y] - 0.2);
        }
    }
    e = 0;
    for (int x=0; x<m; x++){
        for (int y=0; y<m; y++){
            e = e + abs(A[x][y] - B[x][y]);
        }
    }    
}

I would like to run loops at the same time, and not one by one to speed up the execution time. I believe the following code should work, but I'm not sure if I am using OpenMP correctly.

int m = 101;
double e = 10;

double A[m][m], B[m][m];
#pragma omp parallel for private(x,y) shared(A,B) num_threads(2)
for (int x=0; x<m; x++){
    for (int y=0; y<m; y++){
        A[x][y] = 0;
        B[x][y] = 1;
    }
}

while (e >= 0.0001){
    #pragma omp parallel for private(x,y) shared(A,B) num_threads(2)
    for (int x=0; x<m; x++){
        for (int y=0; y<m; y++){
            A[x][y] = 0.25*(B[x][y] - 0.2);
        }
    }
    // I want to wait for the above loop to finish computing before starting the next
    #pragma omp barrier  
    e = 0;
    #pragma omp parallel for private(x,y) shared(A,B,e) num_threads(2)
    for (int x=0; x<m; x++){
        for (int y=0; y<m; y++){
            e = e + abs(A[x][y] - B[x][y]);
        }
    }    
}

Am I using OpenMP efficiently and correctly? Also, I'm not sure if I can use OpenMP for my while loop, since it requires the inner loops to be evaluated before it can determine whether to start again.

+4
1

, , , :

int m = 101;
double e = 10;

double A[m][m], B[m][m];

#pragma omp parallel num_threads(2) shared(A, B)
{

    #pragma omp for
    for (int x=0; x<m; x++){
        for (int y=0; y<m; y++){
            A[x][y] = 0;
            B[x][y] = 1;
       }
    }

   while (e >= 0.0001){
    #pragma omp for
    for (int x=0; x<m; x++){
        for (int y=0; y<m; y++){
            A[x][y] = 0.25*(B[x][y] - 0.2);
        }
    }

    #pragma omp single
    e = 0;

    #pragma omp for reduction (+:e)
    for (int x=0; x<m; x++){
        for (int y=0; y<m; y++){
            e = e + abs(A[x][y] - B[x][y]);
        }
    }    
  }
}

, , , . , 2 , , , , chunk = 1.

x y private, openmp . e = e + abs(A[x][y] - B[x][y]);, , , , "e", " (+: e)", "e" .

+5

Source: https://habr.com/ru/post/1662896/


All Articles