OpenMP creates only one thread

2019-09-03 14:49发布

I use Ubuntu and write several lines of code.But it creates only one thread. When I run on my terminal the nproc command, the output is 2. My code is below

int nthreads, tid;

#pragma omp parallel private(tid)
{
    tid = omp_get_thread_num(); 
    printf("Thread = %d\n", tid);

    /* for only main thread */
    if (tid == 0) 
    {
        nthreads = omp_get_num_threads(); 
        printf("Number of threads = %d\n", nthreads);
    }
}  

The output:

Thread = 0
Number of threads = 1

How can I do parallelism?

1条回答
smile是对你的礼貌
2楼-- · 2019-09-03 15:41

If you are using gcc/g++ you must make sure you enable openmp extensions with the -fopenmp compiler and linker options. Specifying it during linking will link in the appropriate library (-lgomp).

Compile with something like:

g++ -fopenmp myfile.c -o exec

or:

g++ -c myfile.c -fopenmp
g++ -o exec myfile.o -fopenmp

If you leave out the -fopenmp compile option your program will compile but it will run as if openmp wasn't being used. If your program doesn't use omp_set_num_threads to set the number of threads they can be set from the command line:

OMP_NUM_THREADS=8 ./exec

I think the default is is generally the number of cores on a particular system.

查看更多
登录 后发表回答