OpenMP仅创建一个线程 [英] OpenMP creates only one thread

查看:553
本文介绍了OpenMP仅创建一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Ubuntu并编写了几行代码,但是它仅创建一个线程.当我在终端上运行nproc命令时,输出为2.我的代码在下面

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);
    }
}  

输出:

Thread = 0
Number of threads = 1

如何进行并行处理?

推荐答案

如果您使用的是gcc/g ++,则必须确保使用-fopenmp 编译器启用openmp扩展>链接器选项.在链接期间指定它会链接到相应的库(-lgomp).

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

或:

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

如果省略了-fopenmp编译选项,则程序将进行编译,但是它将像未使用openmp一样运行.如果您的程序不使用omp_set_num_threads设置线程数,则可以从命令行设置它们:

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.

这篇关于OpenMP仅创建一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆