cfor-loopparallel-processingopenmpcritical-section

Parallel sections code with nested loops in openmp


I made this parallel code to share the iterations like first and last, fisrst+1 and last-1,... But I don't know how to improve the code in every one of the two parallel sections because I have an inner loop in the sections and I can't think of any way to simplify it, thanks.

This isn't about which values are stored in x or y, I use this sections design because the requisite is execute the iterations from 0 to N like: 0 N, 1 N-1, 2 N-2 but I would like to know if I can optimize the inner loops maintaining this model

int x = 0, y = 0,k,i,j,h;
#pragma omp parallel private(i, h) reduction(+:x, y)
    {
            #pragma omp sections
            {
                    #pragma omp section
                    {
                            for (i=0; i<N/2; i++)
                            {
                                    C[i] = 0;
                                    for (j=0; j<N; j++)
                                    {
                                        C[i] += MAT[i][j] * B[j];
                                    }
                                    x += C[i];
                            }
                    }
                    #pragma omp section
                    {
                            for (h=N-1; h>=N/2; h--) 
                            {
                                    C[h] = 0;
                                    for (k=0; k<N; k++)
                                    {
                                        C[h] += MAT[h][k] * B[k];
                                    }
                                    y += C[h];
                            }
                    }
            }
    }
    x = x + y;

Solution

  • The section construct is to distribute different tasks to different threads and each section block marks a different task so you will not be able to do that iterations in the order you want I answered you here:

    Distribution of loop iterations between threads with a specific order

    But I want to clarify that the requirement to use sections is that each block must be independent of the other blocks.