我正在使用C++中的OpenMP编写并行程序。
我想使用omp_set_num_threads()
控制程序中线程的数量,但它不起作用。
#include <iostream>
#include <omp.h>
#include "mpi.h"
using namespace std;
int myrank;
int groupsize;
double sum;
double t1,t2;
int n = 10000000;
int main(int argc, char *argv[])
{
MPI_Init( &argc, &argv);
MPI_Comm_rank( MPI_COMM_WORLD, &myrank );
MPI_Comm_size(MPI_COMM_WORLD,&groupsize);
omp_set_num_threads(4);
sum = 0;
#pragma omp for reduction(+:sum)
for (int i = 0; i < n; i++)
sum+= i/(n/10);
cout<<"sum="<<sum<<endl;
cout<<"threads="<<omp_get_num_threads()<<endl;
MPI_Finalize();
return 0;
}
程序输出:sum = 4.5e+007
threads=1
如何控制线程的数量?
num_threads
OpenMP 子句选项,是否可以使用变量而不是硬编码数字?例如:int n = 4; #pragma omp parallel ... num_threads(n)
? - Omar Haquenum_threads
子句也接受变量,因此可以在运行时控制线程数。 - Hristo Iliev