openmp runs single threaded on my mac

2019-02-18 13:59发布

问题:

I am trying to parallelize a program using openmp on a Mac, but I can not manage to make it multi-threaded. I've tried building llvm/clang/openmp 3.7.1 from source (after a svn co) as documented, I have also tried using the prebuild versions of clang and OpenMP 3.7.0 given by the llvm project. In each case, the resulting compiler works fine with the -fopenmp flag and produce an executable that links to the openmp runtime.

I use the following openmp 'hello world' program:

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
    int nthreads, tid;

    /* Fork a team of threads giving them their own copies of variables */
    #pragma omp parallel private(nthreads, tid)
    {
        /* Obtain thread number */
        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 disband */
}

I compile using:

clang -fopenmp hello.c -o hello

and then run the resulting program with:

env OMP_NUM_THREADS=2 ./hello

which gives:

Hello World from thread = 0
Number of threads = 1

Any idea?

回答1:

clang < 3.8.0 requires -fopenmp=libomp to generate OpenMP code. clang >= 3.8.0 also supports -fopenmp (-fopenmp=libomp can be used also).