OpenMP仅创建一个线程

编程入门 行业动态 更新时间:2024-10-17 19:26:04
本文介绍了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仅创建一个线程

本文发布于:2023-10-09 05:50:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474878.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   创建一个   OpenMP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!