×

Search anything:

#pragma omp master [explained with example]

Internship at OpenGenus

Get this book -> Problems on Array: For Interviews and Competitive Programming

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:

  1. pragma omp master
  2. When to use pragma omp master?
  3. pragma omp master vs omp single

Pre-requisite:

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.

Geoffrey Ziskovin

Geoffrey Ziskovin

Geoffrey Ziskovin is an American Software Developer and Author with an experience of over 30 years. He started his career with Haskell and has interviewed over 700 candidates for Fortune 500 companies

Read More

Improved & Reviewed by:


OpenGenus Foundation OpenGenus Foundation
#pragma omp master [explained with example]
Share this