【问题标题】:parallel for loop in c++ using MPI使用 MPI 在 C++ 中并行 for 循环
【发布时间】:2018-09-25 11:08:26
【问题描述】:

我正在尝试使我的for 循环在 C++ 中并行。迭代是完全独立的。下面是一个类似的程序,它捕捉了任务的想法。

class A{

    // create experiment 
    // perform experiment
    // append results to file 
    // reset the experiment 

};

main {

    // open a file 

    // instance class
    A a;
    int N = 10000;

    for ( int i = 0; i <= N; i++ ){
        a.do_something()
    }

    // close file
    // return
}

每次迭代都会简单地将其数据打印到输出文件中,顺序也不重要。由于a.do_something() 很长,我想让它平行。我已经安装了MPI,现在对它的基本用法有点熟悉了。

我的逻辑是根据可用处理器的数量将N 范围划分为多个分区。我正在寻求有关如何将我的串行版本与 MPI 并行的一些帮助。我的尝试是:

class A{

    // create experiment 
    // perform experiment
    // append results to file 
    // reset the experiment 

};

main {

    // open a file 

    // instance class
    A a;


    // initialise the MPI 
    int ierr = MPI_Init(&argc, &argv);
    int procid, numprocs;

    ierr = MPI_Comm_rank(MPI_COMM_WORLD, &procid);
    ierr = MPI_Comm_size(MPI_COMM_WORLD, &numprocs);

    // partition = (job size) over (processors). 
    unsigned int partition = N / numprocs;


    int N = 10000;

    for ( int i = 0; i <= N; i++ ){
        a.do_something()
    }



    ierr = MPI_Finalize();
    // close file
    // return
}

但我真的很难拆分 for 循环并且不知道如何继续。

这只会运行两次串行代码(在我的 2 核机器上)。我想将 for 循环拆分为 N/2 块,并让每个线程处理不同的块。

我是否需要保留一个核心以将作业广播到其他核心?我可以遍历分区吗?我在网上搜索并没有太多运气。有什么建议么?

【问题讨论】:

  • for ( 0 --&gt; N) 你不能发布真实代码吗?这种怪异只是分散了重要代码的注意力
  • @user463035818 谢谢你的建议 :)

标签: c++ parallel-processing mpi


【解决方案1】:

当代码的 MPI 部分启动时,将其视为在处理器上运行的独立程序。这意味着您编写的循环在两个处理器上独立运行。例如,一种拆分方法是

for ( int i = rank*partition; i <= rank*partition+partition; i++ )

{
    a.do_something()
}

另外,在使用之前声明 N :-)

【讨论】:

    【解决方案2】:

    一个简单的方法是:

    for ( int i = 0; i <= N; i++ )
    {
       if (i% numprocs != procid) continue;
    
       a.do_something()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-14
      相关资源
      最近更新 更多