Here is a simple “Hello World” program using OpenMP in C:
#include <stdio.h>
#include <omp.h>
int main() {
#pragma omp parallel
{
printf("Hello, World! from thread %d\n", omp_get_thread_num());
}
return 0;
}
Explanation:
#include <omp.h>
: This header file is required to use OpenMP functions and directives.#pragma omp parallel
: This directive tells the compiler to parallelize the following block of code. Multiple threads will execute the block concurrently.omp_get_thread_num()
: This function returns the thread number (ID) of the current thread.
Compilation:
To compile this program, use an OpenMP-compatible compiler like gcc
with the -fopenmp
flag:
gcc -fopenmp hello_world.c -o hello_world
Execution:
When you run the program:
./hello_world
It will print “Hello, World!” from multiple threads, with each thread displaying its thread ID.
Example Output:
Hello, World! from thread 0
Hello, World! from thread 1
Hello, World! from thread 2
Hello, World! from thread 3
The output order may vary depending on how the threads are scheduled by the system.