Example: While Loop
In an OpenMP code, how might one break out of a parallel loop after some condition is met? With a serial code, the ordinary way to do this is with a while loop. However, basic OpenMP seemingly offers only parallel for loops, in which statements like "break" are disallowed. Is this type of functionality, therefore totally missing from the standard?
The answer is no—but to implement a parallel while loop in OpenMP, some work is required. One way to do it is to make use of the task directive introduced in OpenMP 3.0, which is well suited for irregular parallelism of this kind. However, as the following extended C code example shows, the same goal can also be achieved through a combination of the basic directives that we have covered so far.
Our example draws upon all facets of OpenMP that have been described in this roadmap. It consists of a
parallel construct with shared and private variables. A couple of control directives
(critical, flush) play important roles. There are calls to the OpenMP runtime libraries. Take
some time to read both the code and the comments to understand how the elements all work together. Then, you
might want to copy and paste the code into a terminal (try cat > while_omp.c
and then pasting the code below; use gcc -fopenmp
or icc -qopenmp
.)
CVW material development is supported by NSF OAC awards 1854828, 2321040, 2323116 (UT Austin) and 2005506 (Indiana University)