Open-Source Internship opportunity by OpenGenus for programmers. Apply now.
In this article, we have explained the concept of #
pragma omp master, when it is used and compared omp master with omp single.
Table of contents:
- pragma omp master
- When to use pragma omp master?
- pragma omp master vs omp single
Pre-requisite:
- Understand how to use OpenMP to parallelize C++ code from the basics.
pragma omp master
pragma omp master is used to execute a given code segment only once through the master thread and the other threads do not wait for synchronization.
Following is the syntax of using pragma omp master:
#pragma omp master
{
// code segment ...
}
Following is a C++ code example using pragma omp master:
#include <iostream>
int main() {
#pragma omp parallel
{
for (int i = 0; i < 10; ++i) {
#pragma omp master
{
std::cout << "Execution started" << std::endl;
}
}
}
return 0;
}
Set OMP_NUM_THREADS and run it to check the output.
export OMP_NUM_THREADS=8
The print statement will be executed only once. Remove omp single and run again and you will notice the print statement is executed multiple times.
When to use pragma omp master?
One should use pragma omp master when:
- A code segment should be executed once and that also, by master thread
- A code segment should be executed once and other threads should not wait for it / no need for synchronization.
pragma omp master vs omp single
#pragma omp single
The difference between pragma omp master vs omp single is that:
- pragma omp single makes a code segment executed once by any one thread (can be other than master thread)
- pragma omp master does the same but chooses the master thread only.
- pragma omp single makes the other threads wait for synchronization while in case of pragma omp master, other threads do not wait.
With this article at OpenGenus, you must have the complete idea of pragma omp master in depth.