Helloworld

The same as you learn other languages, we start from a simplehelloworld.c

helloworld.c
#include <omp.h>
#include <stdio.h>
int main(int argc, char *argv[]) {

    int nthreads, tid;

    /* Fork a team of threads with each thread having a private tid variable */
    #pragma omp parallel private(tid)
    {

        /* Obtain and print thread id */
        tid = omp_get_thread_num();
        printf("Hello World from thread = %d\n", tid);

        /* Only master thread does this */
        if (tid == 0)
        {
            nthreads = omp_get_num_threads();
            printf("Number of threads = %d\n", nthreads);
        }

    }  /* All threads join master thread and terminate */

}

To compile the OpenMP program:

gcc -o helloworld helloworld.c -fopenmp

To run the OpenMP program:

./helloworld

$ ./helloworld
Hello World from thread = 0
Number of threads = 4
Hello World from thread = 3
Hello World from thread = 2
Hello World from thread = 1

Explanation:

OpenMP has many implementations. If you use different compilers, you should use different compiler flags.

If you are using Mac, you can use clang to compile the code(no need to change code).

# install llvm and libomp
brew install llvm libomp

# compile your code with clang
clang -Xpreprocessor -fopenmp helloworld.c -ohelloworld -lomp

If you are using other compilers besides the two above, you may need to google some corresponding usage.

Last updated