【问题标题】:Operation type in boost mpi collective operationsboost mpi 集合操作中的操作类型
【发布时间】:2020-08-08 12:42:42
【问题描述】:

boost::mpi 中,一些集合操作,例如reduce,需要将操作传递给例程。我不确定这个操作的类型到底应该是什么。

以下最小示例编译时没有警告。

#include <iostream>
#include <boost/mpi/collectives.hpp>

int mysum(int a, int b) { return a + b; }

int main()
{
  boost::mpi::environment env;
  boost::mpi::communicator world;

  int data = world.rank() + 1;
  int data_reduced;
  boost::mpi::reduce(world, data, data_reduced, mysum, 0);
  if (world.rank() == 0)
    std::cout << data_reduced << std::endl;

  return 0;
}

但是,运行超过 1 个任务时会崩溃

$ mpirun -n 2 ./mpi
munmap_chunk(): invalid pointer
...

如下修改代码可使程序运行而不会崩溃。

#include <iostream>
#include <boost/mpi/collectives.hpp>

struct mysum {
  int operator()(int a, int b) { return a + b; }
};

int main()
{
  boost::mpi::environment env;
  boost::mpi::communicator world;

  int data = world.rank() + 1;
  int data_reduced;
  boost::mpi::reduce(world, data, data_reduced, mysum{}, 0);
  if (world.rank() == 0)
    std::cout << data_reduced << std::endl;

  return 0;
}

(我知道这相当于std::plus,程序只是一个例子)

$ mpirun -n 2 ./mpi
3

有什么区别,为什么第二个版本有效?

编辑

问题也出现了,因为mysum 的两个变体都可以称为mysum(....),即两者都是callable。所以在这两种情况下,下面的代码都有效。

template <class Callable, class ArgType>
auto dosomething(ArgType a, ArgType b, Callable&& L) { return L(a, b); }

auto x = dosomething(mysum, 1, 2);

(这基本上等同于std::invoke

【问题讨论】:

    标签: c++ boost mpi


    【解决方案1】:

    看起来这是 boost::mpi 所期望的!

    如果你模仿boost/mpi/operations.h,你的用户定义归约算子可以这样写

    template<typename T>
    struct mysum
    {
      typedef T first_argument_type;
      typedef T second_argument_type;
      typedef T result_type;
      const T& operator()(const T& x, const T& y) const
      {
        return x + y;
      }
    };
    

    然后您的 reduce 调用将如下所示

    boost::mpi::reduce(world, data, data_reduced, std::plus<int>(), 0);
    

    底线,即使你的mysum 是正确的传递给普通C MPI_Op_create(),这也不是boost::mpi 所期望的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-20
      • 2014-06-03
      • 1970-01-01
      • 1970-01-01
      • 2013-02-11
      • 1970-01-01
      • 2017-02-17
      • 1970-01-01
      相关资源
      最近更新 更多