1. Declare program variables at the innermost loop scopeModern programming languages allow to declare program variables at the beginning of the function/procedure, but also in the middle of the source code, for instance. From the point of view of parallelization, we are very interested in loops because they typically are the most time-consuming parts of the program. Thus, we address the following questions:
- When is it valid to declare a program variable within a loop scope, i.e., at the beginning of a loop body?
- What are the advantages of this programming practice for the parallelization of sequential codes with OpenMP?
2. Avoid the use of struct variables in OpenMP clausesOpenMP does not support a field of a struct in a clause. Thus, if the struct variable is a loop-level temporary you can declare it inside of the corresponding loop scope. Otherwise, it is a good programming practice to declare each struct field as an independent variable. In the following example source code we can see a struct variable named a declared inside the external loop for_i. The OpenMP code compiles successfully. In the following example, the struct variable a is declared at the beginning of the procedure, outside the loop for_i. Within the loop for_i the field a.x is private in the scope of the loop. However, there is also a reduction on the field a.y, which is not loop-level temporary and thus cannot be privatized. Thus, this source code raises a compilation error due to lack of support for struct variables in OpenMP clauses. A valid solution is to declared independent variables for struct fields and use them within the loop body. Such an implementation is shown below and compiles successfully as OpenMP clauses are free of struct variables.
ConclusionsIt’s a good practice to follow these recommendation from the beginning when doing parallel programming in C with OpenMP. In addition, following these programming suggestions you will naturally increase the effectiveness of Parallelware to automatically discover parallelism in your sequential code and auto-generating equivalent OpenMP-enabled parallel code. Have you already seen the live demo of Parallelware? If not, just remember that Parallelware guarantees correctness and performance in your OpenMP-enabled parallel code. When you are starting to develop your code, it might be beneficial to compile it with Parallelware as it automatically checks many of the best programming practices in C presented in this articles. If you like this post, please share!
Make Code Parallel
Parallelware Trainer is an interactive, real-time code editor with features that facilitate the learning, usage, and implementation of parallel programming by understanding how and why sections of code can be parallelized.