Is it beneficial to parallelize variable declaration?

107 Views Asked by At

I wonder if it is beneficial when writing a parallel program to insert variables declarations into the parallel section? Because the Amdahl's law says that if more portion of the program is parallel it's better but I don't see the point to parallelize variables declaration and return statements, for example, this is the normal parallel code:

#include <omp.h>

int main(void) {
    int a = 0;
    int b[5];

    #pragma omp parallel
    {
        #pragma omp for
        for (int i = 0; i < 5; ++i) {
            b[i] = a;
        }
    }

    return 0;
}

Will it be beneficial regarding Amdahl's law to write this (so 100% of the program is parallel):

#include <omp.h>

int main(void) {
    #pragma omp parallel
    {
        int a = 0;
        int b[5];
        #pragma omp for
        for (int i = 0; i < 5; ++i) {
            b[i] = a;
        }

        return 0;
    }        
}
1

There are 1 best solutions below

0
On

These codes are not equivalent: in the first case, a and b are shared variables (since shared is the default behavior for variables), in the second case these are thread-private variables that do not exist beyond the scope of the parallel region.

Besides, the return statement within the parallel region in the second piece of code is illegal and must cause a compilation error.

As seen for instance in this OpenMP 4.0 reference card

An OpenMP executable directive applies to the succeeding structured block or an OpenMP construct. Each directive starts with #pragma omp. The remainder of the directive follows the conventions of the C and C++ standards for compiler directives. A structured-block is a single statement or a compound statement with a single entry at the top and a single exit at the bottom.

A block that contains the return statement is not a structured-block since it does not have a single exit at the bottom (i.e. the closing brace } is not the only exit since return is another one). It may not legally follow the #pragma omp parallel directive.