What is OpenMP?

OpenMP (Open Multi-Processing) is a set of compiler directives and an API for programs written in C, C++, or FORTRAN that provides support for parallel programming in shared-memory environments. OpenMP identifies parallel regions as blocks of code that may run concurrently across multiple threads.

Syntax

#pragma omp parallel
{
    // Code block to execute in parallel
}

How OpenMP Works

Application developers insert compiler directives into their code at parallel regions, and these directives instruct the OpenMP run-time library to execute the region in parallel. When OpenMP encounters the #pragma omp parallel directive, it creates as many threads as there are processing cores in the system.

Example: Basic Parallel Region

The following C program demonstrates a simple OpenMP parallel region −

Installation: To compile OpenMP programs, use gcc -fopenmp filename.c on GCC or equivalent flag on other compilers.

#include <omp.h>
#include <stdio.h>

int main() {
    printf("Before parallel region\n");
    
    #pragma omp parallel
    {
        int thread_id = omp_get_thread_num();
        int num_threads = omp_get_num_threads();
        printf("Hello from thread %d of %d\n", thread_id, num_threads);
    }
    
    printf("After parallel region\n");
    return 0;
}
Before parallel region
Hello from thread 0 of 4
Hello from thread 2 of 4
Hello from thread 1 of 4
Hello from thread 3 of 4
After parallel region

Key Features

  • Automatic Thread Creation: Creates threads equal to the number of CPU cores
  • Shared Memory Model: All threads share the same memory space
  • Data Sharing Control: Allows specifying whether variables are shared or private to threads
  • Cross-Platform: Available on Linux, Windows, and Mac OS X systems

Conclusion

OpenMP provides a simple yet powerful way to add parallelism to C programs using compiler directives. It automatically manages thread creation and synchronization, making parallel programming more accessible to developers.

Updated on: 2026-03-15T12:12:51+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements