OpenMP set_num_threads()不工作 [英] OpenMP set_num_threads() is not working

查看:3691
本文介绍了OpenMP set_num_threads()不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中使用OpenMP编写并行程序。

I am writing a parallel program using OpenMP in C++.

我想使用 omp_set_num_threads()来控制程序中的线程数, ,但不起作用。

I want to control the number of threads in the program using omp_set_num_threads(), but it does not work.

#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


$ b

How to control the number of threads?

除了调用 omp_get_num_threads()

解决方案

推荐答案

要强制执行给定数量的线程,您应该禁用动态团队并指定所需的线程数量 omp_set_num_threads()

To enforce a given number of threads you should disable dynamic teams and specify the desired number of threads with either omp_set_num_threads():

omp_set_dynamic(0);     // Explicitly disable dynamic teams
omp_set_num_threads(4); // Use 4 threads for all consecutive parallel regions
#pragma omp parallel ...
{
    ... 4 threads used here ...
}

或与 num_threads OpenMP子句:

or with the num_threads OpenMP clause:

omp_set_dynamic(0);     // Explicitly disable dynamic teams
// Spawn 4 threads for this parallel region only
#pragma omp parallel ... num_threads(4)
{
    ... 4 threads used here ...
}

这篇关于OpenMP set_num_threads()不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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