Open-Source Internship opportunity by OpenGenus for programmers. Apply now.
In this article, we have explained the concept of #
pragma omp single, when it is used and compared omp single with omp critical and omp master.
Table of contents:
- pragma omp single
- When to use pragma omp single?
- pragma omp single vs omp critical
- pragma omp single vs omp master
Pre-requisite:
- Understand how to use OpenMP to parallelize C++ code from the basics.
pragma omp single
pragma omp single is an OpenMP directive that is used to define a code segment that should be executed only once by any one thread from the team. The thread choosen can be other than master thread.
#pragma omp single
{
// code segment ...
}
Following is a C++ code example:
#include <iostream>
int main() {
#pragma omp parallel
{
// private variable
int sum_local = 0;
#pragma omp for nowait
for (int i = 0; i < 10; ++i) {
#pragma omp single
{
std::cout << "Execution started" << std::endl;
}
sum_local += i;
}
}
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 single?
One should use omp single when:
- A particular code segment should be executed only once like a print statement or a control flag indicating a specific occurence.
- Other threads should wait and synchronize
pragma omp single vs omp critical
The difference between pragma omp critical vs omp single is covered in this summary table:
pragma omp critical vs omp single | ||
---|---|---|
Point | omp critical | omp single |
Meaning | Run code segment one by one by all threads | Run code segment once by any thread |
Number of times code is executed | Number of threads | 1 |
Use case | Avoid race condition | Manage control variables or signals |
Following code snippet illustrates the difference between the two:
int a=0, b=0;
#pragma omp parallel num_threads(16)
{
#pragma omp single
a++;
#pragma omp critical
b++;
}
std::cout << "a=" << a << ", b=" << b << std::endl;
The output will be
a=1, b=16
pragma omp single vs omp master
#pragma omp master
The difference between pragma omp single vs omp master 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 how to use pragma omp single in your C++ code.