OpenMP creates only one thread

安稳与你 提交于 2019-12-11 14:47:34

问题


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:


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.



来源:https://stackoverflow.com/questions/26049965/openmp-creates-only-one-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!