我使用OpenMP编写了以下C/C++代码:
int nProcessors=omp_get_max_threads();
if(argv[4]!=NULL){
printf("argv[4]: %s\n",argv[4]);
nProcessors=atoi(argv[4]);
printf("nProcessors: %d\n",nProcessors);
}
omp_set_num_threads(nProcessors);
printf("omp_get_num_threads(): %d\n",omp_get_num_threads());
exit(0);
如您所见,我正在尝试根据在命令行上传递的参数来设置要使用的处理器数量。
但是,我得到了以下输出:
argv[4]: 2 //OK
nProcessors: 2 //OK
omp_get_num_threads(): 1 //WTF?!
为什么omp_get_num_threads()
不返回2?!
如前所述,我在串行区域调用omp_get_num_threads()
,因此该函数返回1
。
但是,我有以下并行代码:
#pragma omp parallel for private(i,j,tid,_hash) firstprivate(firstTime) reduction(+:nChunksDetected)
for(i=0;i<fileLen-CHUNKSIZE;i++){
tid=omp_get_thread_num();
printf("%d\n",tid);
int nThreads=omp_get_num_threads();
printf("%d\n",nThreads);
...
以下哪项输出:
0 //tid
1 //nThreads - this should be 2!
0
1
0
1
0
1
...
发布于 2012-01-23 17:58:12
omp_get_num_threads()
调用在代码的串行部分返回1。请参阅Link
所以你需要使用并行代码来获得正确的值,下面是你的代码应该是什么样子的:
#include <iostream>
#include <omp.h>
int main (int argc, const char * argv[])
{
int nProcessors = omp_get_max_threads();
std::cout<<nProcessors<<std::endl;
omp_set_num_threads(nProcessors);
std::cout<<omp_get_num_threads()<<std::endl;
#pragma omp parallel for
for(int i = 0; i < 5; i++){
int tid = omp_get_thread_num();
std::cout<<tid<<"\t tid"<<std::endl;
int nThreads = omp_get_num_threads();
std::cout<<nThreads<<"\t nThreads"<<std::endl;
}
exit(0);
}
这段代码产生:
2
1
0 tid
2 nThreads
0 tid
2 nThreads
0 tid
2 nThreads
1 tid
2 nThreads
1 tid
2 nThreads
您似乎没有启用open mp,或者您的循环不是可以由openmp并行的形式。
发布于 2012-01-23 20:44:33
您使用了错误的函数。使用omp_get_max_threads
检查允许的最大线程数。
发布于 2017-03-13 17:29:45
前面已经指出,omp_get_num_threads()
在代码的连续部分中返回1
。因此,即使omp_set_num_threads()
设置的线程总数大于1
,任何对omp_get_num_threads()
的调用都将返回1
,除非我们在并行段中。下面的例子试图阐明这一点。
#include <stdio.h>
#include <omp.h>
int main() {
const int maxNumThreads = omp_get_max_threads();
printf("Maximum number of threads for this machine: %i\n", maxNumThreads);
printf("Not yet started a parallel Section: the number of threads is %i\n", omp_get_num_threads());
printf("Setting the maximum number of threads...\n");
omp_set_num_threads(maxNumThreads);
printf("Once again, not yet started a parallel Section: the number of threads is still %i\n", omp_get_num_threads());
printf("Starting a parallel Section...\n");
#pragma omp parallel for
for (int i = 0; i < maxNumThreads; i++) {
int tid = omp_get_thread_num();
printf("This is thread %i announcing that the number of launched threads is %i\n", tid, omp_get_num_threads());
}
}
https://stackoverflow.com/questions/8969748
复制相似问题