Open In App

C – Parallel for loop in OpenMP

Prerequisites:

  1. OpenMP | Introduction with Installation Guide
  2. OpenMP Hello World Program

We have the for loops in the programs and we can parallelize them easily with the help of OpenMP Library. Add #include<omp.h>, as all the prototypes for these parallelization techniques of OpenMP lie in that header file.



Syntax:

#pragma omp parallel for [clause[[,] clause] ...] new-line
for-loop

Explanation:



 

Algorithm:

  1.  Start the program
  2. There are many for loops in the program.
  3. Add the for loop construct before all the for loops.
  4. num_threads( n ) needs to be mentioned to get n threads
  5. If not mentioned, by default, the no. of processor’s scores threads are formed.
  6. So therefore parallelized.

Example:




#include <omp.h>
#include <stdio.h>
 
int main()
{
 
    #pragma omp parallel for num_threads(4)
    for (int i = 1; i <= 10; i++) {
        int tid = omp_get_thread_num();
        printf("The thread %d  executes i = %d\n", tid, i);
    }
 
    return 0;
}

Output:

Output

Time Complexity: O(N)

Space Complexity: O(1)

Article Tags :